如果您在弹出或背景或选项页面中,则有一种间接方法可以获取页面域。
您可以参考以下代码作为参考。
示范
清单.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);
}
});
});
背景.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()
输出。
但是,内容脚本输出总是
http://somedomain.com/
参考