Code in content_scripts not executed when document changes?

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:

"matches": ["<all_urls>"],

or
“matches”: ["://github.com/mdn/"],
(See https://github.com/mdn/webextensions-examples/tree/main/borderify)

This is an example of the problematic behaviour:

I navigate to ‘https://github.com/mdn/webextensions-examples/’ with firefox, the colored border appears.

In this page, I click the ‘annotate-page’ link, which navigates me to ‘https://github.com/mdn/webextensions-examples/tree/main/annotate-page’, but the colored border does NOT appear.

When I refresh the page with F5, the colored border is drawn.

Clicking the browsers ‘back’ button, the previous page is shown, but WITHOUT the border. Refreshing with F5 makes the border appear again.

So my question:

Why doesn’t the code in the content_scripts work whenever the document
changes? How can I fix this?

Thanks, Thomas

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.

Very usefull hint! Thanks for that.

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 :smiley:.
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.

Thanks, now I have quite something to try… :grinning: