Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading a Chrome extension content script execution environment

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.

like image 783
Mispy Avatar asked Oct 14 '13 06:10

Mispy


People also ask

How do I reload Chrome extensions?

1 - The extension's toolbar button. 2 - Browsing to "http://reload.extensions". The toolbar icon will reload unpacked extensions using a single click.

What is content script Chrome extension?

A content script is a part of your extension that runs in the context of a particular web page (as opposed to background scripts which are part of the extension, or scripts which are part of the website itself, such as those loaded using the <script> element).

What is Chrome extension inject JS?

JS Inject. Create, save, and inject javascript code into web pages. This extension allows you to write, save, and execute javascript into web pages. You can save scripts to be run globally (on any page), on a specific domain, on a specific page, or via a "URL contains" string.


1 Answers

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() {});
    }
});
like image 128
Métoule Avatar answered Oct 22 '22 21:10

Métoule