Zizheng Tai
Zizheng Tai

Reputation: 6616

Chrome extension - load content script on URL updates

I'm having this problem where I want to run a content script content.js on pages with URLs matching https://www.example.com/*. I have defined in manifest.json the following:

{ 
  ...

  "content_scripts": [
    {
      "matches": ["https://www.example.com/*"],
      "js": ["content.js"]
    }
  ],

  ...
}

However, content.js will not be loaded when the user navigates from another page (say https://www.foo.bar) to https://www.example.com/*, for example by clicking a hyperlink. It's only loaded when the user directly visits https://www.example.com/*.

I'm considering injecting content.js into all pages, and listening for chrome.tabs.onUpdate in the background to see if the current URL matches https://www.example.com/*, and depending on that send messages to content.js. Is there a better way to work around this?

Upvotes: 1

Views: 539

Answers (1)

Mike Tyukanov
Mike Tyukanov

Reputation: 604

You can inject your script programmatically from the background page, making the function where you are to send/receive messages executeScript's callback:

function processUrl(tabId, url) {
  if(url.indexOf("https://www.example.com")>-1){
    chrome.tabs.executeScript(tabId, {file:"content.js"}, function() {
      //send and receive msgs  here
    };
  }
}

Then just call this function from your listener(s). If you want to use a library or other dependency, call executeScript with the library first, and executeScript with your script in the first call's callback.

Upvotes: 1

Related Questions