After the Chrome extension I’m working on is installed, or upgraded, the content scripts (specified in the manifest) are not re-injected so a page refresh is required to make the extension work. Is there a way to force the scripts to be injected again?
I believe I could inject them again programmatically by removing them from the manifest and then handling which pages to inject in the background page, but this is not a good solution.
I don’t want to automatically refresh the user’s tabs because that could lose some of their data. Safari automatically refreshes all pages when you install or upgrade an extension.
There’s a way to allow a content script heavy extension to continue functioning after an upgrade, and to make it work immediately upon installation.
Install/upgrade
The install method is to simply iterate through all tabs in all windows, and inject some scripts programmatically into tabs with matching URLs.
ManifestV3
manifest.json:
These host_permissions should be the same as the content script’s
matches.background.js:
This is a simplified example that doesn’t handle frames. You can use getAllFrames API and match the URLs yourself, see the documentation for matching patterns.
Caveats & Notes
Cannot access contents of the page. Extension manifest must request permission to access the respective host.You will need to refresh those tabs so that they now have the new extension code that will auto-reload them.Error: Extension context invalidated.If you are still receiving this you will need to remove any old event handlers on the page for the content script see: Chrome Extension: How to remove orphaned script after Chrome extension updateManifestV2
Obviously, you have to do it in a background page or event page script declared in manifest.json:
background.js:
Historical trivia
In ancient Chrome 26 and earlier content scripts could restore connection to the background script. It was fixed http://crbug.com/168263 in 2013. You can see an example of this trick in the earlier revisions of this answer.