获取域名的javascript google chrome扩展程序

hel*_*llo 4 javascript google-chrome cross-domain google-chrome-extension

我尝试使用域名,alert(document.domain);但是当我在网站上测试时,我没有获得正确的域名,

我得到了"hiecjmnbaldlmopbbkifcelmaaalcfib"这个奇怪的输出.

我也在清单中添加了这个

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

        }
  ],
Run Code Online (Sandbox Code Playgroud)

警报(document.domain的); 是inject.js中唯一的文本行.

我之后将其合并<script type="text/javascript" src="inject.js"> </script>到主html文件中popup.js

有关为什么我没有获得正确的域名网址的任何想法?

谢谢!

Sud*_*han 6

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

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

示范

的manifest.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>"
    ]
}
Run Code Online (Sandbox Code Playgroud)

myscript.js

console.log(document.domain);// Outputs present active URL of tab
Run Code Online (Sandbox Code Playgroud)

popup.html

注册popup.js超过CSP.

<html>

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

    <body></body>

</html>
Run Code Online (Sandbox Code Playgroud)

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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

产量

你会找到

fgbhocadghoeonlokakijhnlplgkolbg

作为console.log(document.domain)的输出; 在所有扩展页面和

http://somedomain.com/

tabs.query()输出.

但是,内容脚本输出始终是

http://somedomain.com/

参考