11
votes

I’d like to mimic the effect of window.location.reload(), but only for the “isolated world” which my content script is running in. That is, remove all existing JS, particularly callbacks and event bindings. Is there a nice way to do this?

Note: chrome.runtime.reload() doesn’t work for this; it has the effect of reloading the extension and the background script, but it does not reload existing content scripts until the user refreshes.

1

1 Answers

7
votes

As far as I can tell, there's no automatic way to re-inject content scripts, for example during an extension update. What you can do is to find all tabs whose url matches the pattern you need, and programmatically re-inject the content scripts using chrome.tabs.executeScript.

Note that this method requires to add a permission for the same URL pattern as the one used by your content script.

Manifest.json:

"content_scripts":    
[
    {
        "matches": [ "http://*.google.com/*" ],
        "js": [ "content_script.js" ]
    }
], 
"permissions":        
[ 
    "tabs", "http://*.google.com/*"
]

Background.js:

chrome.runtime.reload();
chrome.tabs.query({ url: "http://*.google.com/*" }, function(tabs)
{
    for(var i = 0; i < tabs.length; i++)
    {
        chrome.tabs.executeScript(tabs[i].id, { file: "content_script.js" }, function() {});
    }
});