Content script not working unless page reloaded

First-timer here. I made an add-on to highlight/modify prices on a specific website. It works when I first load the page, but when I use the page’s sort/filter options, the prices go back to their normal display. If I reload the page, my changes show up again. Advice appreciated, thanks.

manifest.json (partial)

...
"content_scripts": [
	{
		"matches": ["\*://\*.example.com/\*"],
		"js": ["content_script.js"],
		"run_at": "document_end"
	}
],
...

content_script.js

(function() {
    window.addEventListener("load", main, false);
    function main() {
        let t = setInterval(done, 100);
        function done() {
            pricingInfo = document.querySelectorAll(".pricing-info");
            if (pricingInfo.length > 0) {
                clearInterval(t);
                updateAllPrices();
            }
        }
    }
    function updateAllPrices() {
        pricingInfo.forEach((price) => {
            let origPrice = price.innerText;
            let realPrice = origPrice.replace("$", "");
            realPrice = parseFloat(realPrice / 0.89).toFixed(2);
            
            price.innerText = "";  // hide unwanted price info
            
            origSpan = document.createElement("span");
            realSpan = document.createElement("span");
            
            origSpan.append(origPrice);
            realSpan.append(" $" + realPrice);
            
            origSpan.setAttribute("style", "color:#ddd;text-decoration:line-through;");
            price.appendChild(origSpan);
            price.appendChild(realSpan);
        });
    }
})();

Many webpages are now a “web-application”, so their content can change using javascript without reloading the page.

So you need to “observe” the changes and re-apply your highlighting.
There is MutationObserver API for that, but it’s not exactly trivial to use. Also it’s easy to get into infinite loop so be careful.

PS:
I’ve made a similar addon - Auto Highlight. It can be used to highlight things on pages…

1 Like