1

I have an extension that injects content scripts when the tab is updated. Main script:

chrome.browserAction.onClicked.addListener(function(tab) {
 "use strict";
 const sendScriptToPage = function(tabId, changeInfo, tab) {
 if (changeInfo.status === "complete" && tab && tab.url && tab.url.indexOf("http") === 0) {
 console.log ("executeScript ");
 chrome.tabs.executeScript(tabId, {
 file: "content.js", allFrames: true
 });
 }
 };
 chrome.tabs.onUpdated.addListener(sendScriptToPage);
});

Content script:

const Content = (function() {
 "use strict";
 console.log("Content");
 const makeRandomColor = function(){
 let c = '';
 while (c.length < 6) {
 c += (Math.random()).toString(16).substr(-6).substr(-1)
 }
 return '#'+c;
 };
 document.body.style.backgroundColor = makeRandomColor();
}
)();

It works fine when I reload a tab. However, when a tab is reloaded dynamically, the content script gets reloaded although it is already loaded in the tab. This shows in the log since const can't be re-declared.

Should not content scripts be unloaded when an update occurs? How can I know if a content script is already loaded or not?

A URL that shows this behaviour: http://www.prisjakt.nu/produkt.php?p=391945#rparams=ss=android

Typing something in the search field triggers the onUpdated event handler, but the content script is already in the page.

A test extension: https://github.com/hawk-lord/chrome-test

mkluwe
4,0893 gold badges32 silver badges51 bronze badges
asked May 24, 2016 at 17:13

1 Answer 1

1

A navigation would wipe the content scripts, but onUpdated can be triggered by many things.

The first that comes to mind is an iframe being loaded. The main page doesn't navigate but you do inject indiscriminately.

Many approaches are possible:

  1. Make the content script more robust by checking for Content being defined before you do anything.
  2. Listen to a different event, for example, various webNavigation API events. They will uniquely identify the frame they refer to.
  3. Don't listen to events - always inject, and change your triggering logic (for instance, keep a flag in chrome.storage).
answered May 24, 2016 at 19:44
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. The first approach seems to be the most convenient.
Interesting and learning from this question and trying to apply it to urgent matter I have with a chrome extension that needs page refresh in order for it to work. superuser.com/questions/1320599/…?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.