mehulmpt
mehulmpt

Reputation: 16577

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. 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?

Upvotes: 1

Views: 1227

Answers (1)

Marco Bonelli
Marco Bonelli

Reputation: 69346

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.

NOTE: since January 2021, use Manifest V3 with chrome.scripting.executeScript() instead of 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:

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

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

Then, in your background.js, add the listener for 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"});
    }
});

The above code will inject your getCurrentURL.js script, which contains the code you use to display the 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. So your getCurrentURL.js will look like this:

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

Upvotes: 3

Related Questions