【问题标题】:javascript google chrome extension getting domain namejavascript 谷歌浏览器扩展获取域名
【发布时间】:2013-01-25 15:28:10
【问题描述】:

我尝试使用alert(document.domain); 获取域名,但是当我在站点中进行测试时,我没有得到正确的域,

我得到“hiecjmnbaldlmopbbkifcelmaaalcfib”这个奇怪的输出。

我也在清单中添加了这个

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

        }
  ],

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

我已经将这个<script type="text/javascript" src="inject.js"> </script> 合并到了popup.js 之后的主html 文件中

对为什么我没有得到正确的域 url 有什么想法吗?

谢谢!

【问题讨论】:

  • window.top.location 呢?
  • “奇怪”输出是您的应用程序的 id,您期望的域值是多少?
  • @lostsource stackoverflow, latimes, yahoo, etc...各种域名
  • @EliranMalka 出于某种原因window.top.location 不断输出chrome-extension://(the app id)/popup.html?

标签: javascript google-chrome google-chrome-extension cross-domain


【解决方案1】:

如果您在弹出或背景或选项页面中,则可以通过间接方法获取页面的域。

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

演示

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>"
    ]
}

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() 输出。

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

http://somedomain.com/

参考文献

【讨论】:

  • 哇,这帮了大忙!你能解释一下对 background.js 的需求吗?
  • @andrewliu:我刚刚展示了一种使用 background.js 的替代方法,供您参考..
猜你喜欢
  • 2016-09-02
  • 1970-01-01
  • 2011-10-15
  • 2015-04-17
  • 2014-07-24
  • 2016-06-08
相关资源
最近更新 更多