我正在尝试获取 Chrome 中当前选项卡的当前 URL。但是当我更改选项卡时,这不会刷新。
document.addEventListener('DOMContentLoaded', function () {
document.getElementsByTagName('body')[0].innerHTML = document.location;
});
足够简单。它运行良好,但当我切换选项卡时它显示相同的位置。我该如何克服这个问题?
最佳答案
在后台页面中,您应该向 chrome.tabs.onUpdated
事件添加一个监听器,并将脚本注入(inject)到您想要的选项卡中(例如,某个选项卡的某个 URL 与 RegExp
模式)使用 chrome.tabs.executeScript()
方法。
注意:自 2021 年 1 月起,请使用 Manifest V3与 chrome.scripting.executeScript()
而不是 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"});
}
});
上面的代码将注入(inject)您的 getCurrentURL.js
脚本,其中包含您用于显示 URL 的代码。另外,您不需要等到 DOMContentLoaded
,因为如果您使用 runAt: "document_end"
,Chrome 将等到 DOM 加载后再注入(inject)。因此,您的 getCurrentURL.js
将如下所示:
document.body.innerHTML = location.href;
// use location.href instead of document.location if you want the url
关于javascript - 如何在选项卡切换 Google Chrome 扩展上获取新 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26384241/