JavaScript 谷歌浏览器扩展获取域名

4

我尝试使用 alert(document.domain); 获取域名,但当我在网站上测试时,没有得到正确的域名,我得到了这个奇怪的输出 "hiecjmnbaldlmopbbkifcelmaaalcfib"。

我已经将这个代码添加到清单文件中。

  "content_scripts": [
        {
        "js": ["inject.js"]

        }
  ],

alert(document.domain); 是 inject.js 文件中唯一的文本行。

我已经将 <script type="text/javascript" src="inject.js"> </script> 这段代码嵌入到了 popup.js 后面的主 html 文件中。

你有什么想法,为什么我没有得到正确的域名 url?

谢谢!


window.top.location 怎么样? - Eliran Malka
3
“奇怪的”输出是您的应用程序的ID,您期望什么域值? - lostsource
1
@lostsource、stackoverflow、latimes、yahoo等等各种域名。 - hellomello
@EliranMalka,由于某种原因,window.top.location不断输出chrome-extension://(the app id)/popup.html - hellomello
1个回答

7

如果您在弹出窗口、后台或选项页面中,有一种间接的方法可以获取页面的域。

您可以参考以下代码作为参考。

演示

manifest.json

在清单文件中注册内容脚本、后台和弹出窗口脚本,同时申请相关权限。

{
    "name": "Domain Name",
    "description": "https://dev59.com/8m7Xa4cB1Zd3GeqPoEl1",
    "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

弹出窗口.html

注册popup.js以绕过内容安全策略。

<html>

    <head>
        <script src="popup.js"></script>
    </head>

    <body></body>

</html>

popup.js

DOM 内容加载完成 添加事件监听器,并获取用户所在标签页的活动 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);
    }
});

输出

在所有扩展页面中,使用console.log(document.domain)将会得到以下输出:

fgbhocadghoeonlokakijhnlplgkolbg

而对于tabs.query()的输出,则为:

http://somedomain.com/

然而,内容脚本输出始终为:

http://somedomain.com/

参考文献


哇,这帮了很多!你能解释一下 background.js 的必要性吗? - hellomello
@andrewliu:我刚刚展示了一种使用 background.js 的替代方法,供您参考。 - Sudarshan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接