javascript - 如何在选项卡切换 Google Chrome 扩展上获取新 URL?

标签 javascript google-chrome google-chrome-extension

我正在尝试获取 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 V3chrome.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/

相关文章:

html - Mozilla 外观 Checkbox

google-chrome - 在 Chrome 扩展程序中生成下载文件的 md5/sha1/sha256 哈希

javascript - 带有 chrome 扩展的 Google 表格 API,如何使用?

javascript - 在 HTML 文件中加载 json 文件

javascript - 我想让我的菜单效果消失

javascript - 将数据属性添加到 selectize.js 选项

css - 带有指纹 Assets 的 Chrome 工作区

javascript - KO 的组件层次结构(或缺乏)

javascript - 从 Chrome 扩展程序连接到数据库?

javascript - 我可以将 Google Analytics 添加到没有 popup.html 的 Chrome 扩展程序吗?