I am working on an add-on that will inject some javascript into certain web pages. Which works nicely but has one problem: when I navigate to a different page the code is not always injected unless I refresh the loaded page with the F5 key.
The same behaviour also appears on certain pages with the Borderify example (which draws a border around the document body) where I have changed the manifest.json code to match these pages:
This happens because modern websites are often a web-application. So when you navigate to a sub-page, the page doesn’t reload, only content of the existing page is modified (page can modify also URL!).
You can tell (usually) whether the page is a web-app, by looking at the loading indicator (the favicon in the tab). When it changes to the animated “loading” icon, it’s a normal webpage load.
But if during the navigation it doesn’t change and it’s still a favicon of the page, it’s an app.
What this means for you, is that your content script is still there, it’s still running, but the page redrawn it’s content, so your changes are gone.
There is no easy solution!
You could try to detect URL change and re-apply changes.
Modern and more stable solution would be using MutationObserver:
But it’s not easy to use. And you can easily cause infinite loop (if page/another addon also has MutationObserver), so it’s best to add some kind of “fail-safe” mechanism when using it.
You mean detecting URL change with the MutationObserver?
Or how can I detect an URL change (I guess there is no event for that? - sorry, this is my first addon)
Yeah, the detecting URL change is also not easy .
The best I could find is this:
The MutationObserver is for detecting changs in the page, so you would register it on the document body and watch for all changes, and when the change affects whatever you need to modify, you would re-apply the changes.