ポップアップ、バックグラウンド、またはオプション ページにいる場合、ページのドメインを取得するための間接的な方法があります。
以下のコードを参考にしてください。
デモンストレーション
マニフェスト.json
登録されたコンテンツ スクリプト、バックグラウンドおよびポップアップ スクリプトとマニフェスト ファイル、および関連する権限
{
"name": "Domain Name",
"description": "http://stackoverflow.com/questions/14796722/javascript-google-chrome-extension-getting-domain-name",
"version": "1",
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"myscript.js"
]
}
],
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"tabs",
"<all_urls>"
]
}
myscript.js
console.log(document.domain);// Outputs present active URL of tab
popup.html
popup.js
CSPを凌駕するために登録されました。
<html>
<head>
<script src="popup.js"></script>
</head>
<body></body>
</html>
popup.js
のイベント リスナーを追加しDOM Content Loaded
、ユーザーがオンになっているタブの URL をアクティブにしました。
document.addEventListener("DOMContentLoaded", function () {
console.log(document.domain);//It outputs id of extension to console
chrome.tabs.query({ //This method output active URL
"active": true,
"currentWindow": true,
"status": "complete",
"windowType": "normal"
}, function (tabs) {
for (tab in tabs) {
console.log(tabs[tab].url);
}
});
});
background.js
console.log(document.domain); //It outputs id of extension to console
chrome.tabs.query({ //This method output active URL
"active": true,
"currentWindow": true,
"status": "complete",
"windowType": "normal"
}, function (tabs) {
for (tab in tabs) {
console.log(tabs[tab].url);
}
});
出力
見つけるだろう
fgbhocadghoeonlokakijhnlplgkolbg
console.log(document.domain) の出力として; すべての拡張ページと
と
http://somedomain.com/
出力用tabs.query()
。
ただし、Content スクリプトの出力は常に
http://somedomain.com/
参考文献