21

I have a content script that is run when the user connects to "*://www.youtube.com/*". I need to know when the URL changes, as YouTube does not open a new 'page', so-to-speak, when you click on a link; rather it changes the URL and page contents (I think). Because of this, my content script doesn't realize that anything has changed. (I know this because it DOES work when I reload the page)

So how do I find out when the URL of the tab that my script is running in has changed?

[Edit]: My question concerns specifically getting the URL of the tab that the content script is running in, rather than getting the url of the active tab.

4
  • Possible duplicate of Get current URL for Chrome extension
    – Fohlen
    Commented Nov 29, 2016 at 20:07
  • @Fohlen, This question is not a duplicate of that question. That question is specifically regarding getting the URL of the tab from within a chrome.contextMenus (which its primary answer reflects). Looking at the code from that answer it is clear that, despite there being better solutions (as answered), that question is actually a duplicate of the question listed in comments as a possible duplicate.
    – Makyen
    Commented Nov 29, 2016 at 21:29
  • How did you manage to actually get this working? Specifically for the youtube case, how did you manage to detect that the page had changed?
    – pingOfDoom
    Commented Jun 26, 2020 at 2:13
  • @pingOfDoom I periodically checked the location.href, every half/full second or so.
    – otoomey
    Commented Jun 26, 2020 at 22:07

2 Answers 2

46

location.href is a simple way to get the active URL https://developer.mozilla.org/en-US/docs/Web/API/Window/location

3
  • 1
    Sometimes the best answer is the simplest :)
    – Badrush
    Commented Sep 26, 2021 at 4:02
  • document.location.href would be more precise and direct to use!! right ? Commented Dec 29, 2021 at 14:42
  • but how would you listen to change for that ? Commented Nov 20, 2023 at 6:05
0

In your background script, you can listen for tab events and send it to your content script. An example is this,

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (changeInfo.url) {
    chrome.tabs.sendMessage(tabId, { tabChanged: true, title: tab.url });
  }
});

It checks if the tab url is being changed and then send the current url to the content script. On the content script, you can collect the information by listening for events sent by the background script

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
   if (message.tabChanged === true) {
    console.log("url changed")
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.