简体   繁体   English

如何在Tab Switch Google Chrome扩展程序上获取新的URL?

[英]How To Get New URL on Tab Switch Google Chrome Extension?

I'm trying to get the current URL of the CURRENT tab in chrome. 我正在尝试在chrome中获取CURRENT选项卡的当前URL。 But this does not refresh when I change the tab. 但这在我更改选项卡时不会刷新。

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

Simple enough. 很简单。 It works well, but it shows the same location when I switch tabs. 它运作良好,但是当我切换标签时它显示了相同的位置。 How do I overcome this? 我该如何克服呢?

In your background page, you should add a listener to the chrome.tabs.onUpdated event, and inject the script inside the tab you want (for example a tab that has some URL matching a RegExp pattern) using the chrome.tabs.executeScript() method. 在背景页面中,您应该将监听器添加到chrome.tabs.onUpdated事件中,然后使用chrome.tabs.executeScript() )将脚本注入所需的标签(例如,具有与RegExp模式匹配的URL的标签)中。 chrome.tabs.executeScript()方法。

Fist of all, in your manifest.json , add the permission for the tabs API, and the "background" field , if you don't have it already: 首先,在manifest.json添加tabs API的权限以及"background"字段 (如果还没有的话):

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

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

Then, in your background.js , add the listener for chrome.tabs.onUpdated : 然后,在您的background.jschrome.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"});
    }
});

The above code will inject your getCurrentURL.js script, which contains the code you use to display the URL. 上面的代码将注入您的getCurrentURL.js脚本,其中包含用于显示URL的代码。 Plus, you don't need to wait until DOMContentLoaded , because if you use runAt: "document_end" , Chrome will wait until the DOM loads before injecting it . 另外, 您不需要等到DOMContentLoaded ,因为如果您使用runAt: "document_end"Chrome将等到DOM加载后再注入 So your getCurrentURL.js will look like this: 因此,您的getCurrentURL.js将如下所示:

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

WORKING EXAMPLE: DOWNLOAD HERE . 工作示例:在此处下载。

Hope I helped you achieving what you wanted! 希望我能帮助您实现您想要的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM