How to replace the CSS of a content script without reloading the tab

The background script of my extension dynamically registers content scripts based on the user settings. When the user’s settings are updated, the background script unregisters the previous content script and registers the new one using the Content Script API. The content script applies a CSS to the page using the CSS property in the content script object.

The issue with this approach is that the CSS changes are not actually applied to open tabs until the user refreshes each tab or navigates to a new page.

Is there a way to modify or remove the CSS that has been applied to an open tab when I unregister the previous content script?

I know I could do this using JavaScript instead to inject a <style> element onto the page and then just call another script to change the text content of that element. But the issue with that approach is that there’s a delay between when the page is loaded and when the <style> element is created.

1 Like

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/contentScripts/register also allows you to register CSS that is added to the page. However I fear that your CSS modifications are likely created ad-hoc?

1 Like

My code is here: https://github.com/WesleyBranton/Facebook-Like-Hider

It would be nice if when a content script is unregistered, the CSS and JS that’s been injected into the page was automatically removed.

Ah, you are using the content script to directly inject CSS. I think the CSS isn’t removed until the page is reloaded, same goes for JS. I’m not sure if there’s a deeper reason behind it apart from it being the least likely to interrupt whatever the user is currently doing in the tab.

1 Like

It’s a shame there’s no way to update a content script. When you make a new content script, I’m pretty sure that it’s automatically added to open tabs.