如何在Tab切换谷歌Chrome扩展程序上获取新网址?

时间:2014-10-15 13:48:31

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

我正在尝试获取chrome中CURRENT选项卡的当前网址。但是当我更改标签时,这不会刷新。

document.addEventListener('DOMContentLoaded', function () {
  document.getElementsByTagName('body')[0].innerHTML = document.location;
});

足够简单。它运行良好,但当我切换标签时它显示相同的位置。我该如何克服这个问题?

1 个答案:

答案 0 :(得分:1)

在后台页面中,您应该为chrome.tabs.onUpdated事件添加一个侦听器,并将脚本注入所需的选项卡(例如,具有某个匹配RegExp模式的URL的选项卡) chrome.tabs.executeScript()方法。

所有的拳头,在您的manifest.json添加tabs API和"background"字段的权限,如果您没有已:

...
"permissions": [
    "tabs",
    "<all_urls>"
],

"background": { 
    "scripts": [
        "background.js"
    ]
},
...

然后,在background.js添加chrome.tabs.onUpdated 的监听器:

var myRegExp = /https?:\/\/stackoverflow\.com/;
// use a regexp to match the URLs you want
// for example, this will only match stackoverflow.com pages

chrome.tabs.onUpdated.addListener(function(tabID, info, tab) {
    if (myRegExp.test(tab.url)) { // if the url matches, inject your script
        chrome.tabs.executeScript(tabID, {file: "getCurrentURL.js", runAt: "document_end"});
    }
});

上面的代码将注入您的getCurrentURL.js脚本,其中包含用于显示URL的代码。另外,您无需等到DOMContentLoaded ,因为如果您使用runAt: "document_end" Chrome会在注入之前等待DOM加载 。因此,您的getCurrentURL.js将如下所示:

document.body.innerHTML = location.href;
// use location.href instead of document.location if you want the url

工作示例:下载HERE

希望我帮助你实现你想要的目标!

相关问题