[英]How To Get New URL on Tab Switch Google Chrome Extension?
我正在尝试在chrome中获取CURRENT选项卡的当前URL。 但这在我更改选项卡时不会刷新。
document.addEventListener('DOMContentLoaded', function () {
document.getElementsByTagName('body')[0].innerHTML = document.location;
});
很简单。 它运作良好,但是当我切换标签时它显示了相同的位置。 我该如何克服呢?
在背景页面中,您应该将监听器添加到chrome.tabs.onUpdated
事件中,然后使用chrome.tabs.executeScript()
)将脚本注入所需的标签(例如,具有与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
工作示例:在此处下载。
希望我能帮助您实现您想要的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.