0

My extension has a button that injects a stylesheet with insertCSS. When they press the button again, it'll inject the again, causing a repaint. How can I best prevent this?

My current solution: keep an array in the background script with every tabId that has CSS inserted. I remove the tabId from the array when a tab is unloaded. Works fine, but it seems this could be simpler. E.g. window.insertedCSS = true, but doing this from the background script affects all tabs.

RoelN
  • 2,181
  • 13
  • 15
  • 1
    See [Chrome extension: Checking if content script has been injected or not](//stackoverflow.com/a/34529045) - you can even simplify it by using an embedded `code` instead of `file`. – wOxxOm May 07 '19 at 10:28
  • Thanks, @wOxxOm. I don't know why I didn't find that thread, but this is exactly what I need! – RoelN May 07 '19 at 11:07

1 Answers1

0

You can use a content script to check if the CSS was already injected before actually injecting it, like:

function myButtonClicked(){
    chrome.tabs.executeScript({code:`
        (function(){
            if (window.insertCSS === true) return false; //if already inserted return false;
            window.insertCSS = true;            //if not, set the page's variable and return it
            return true;
        })();
    `}, function (result) {
        if (result[0]) {  //if CSS was not inserted, insert it.
           chrome.tabs.insertCSS({file:'myCSS.css'});
        }
    });
}
Iván Nokonoko
  • 4,888
  • 2
  • 19
  • 27
  • Thanks. This didn't work for me until I wrapped the code in an anonymous function, much like @wOxxoM's answer. Maybe you can edit that and I'll accept your answer? – RoelN May 07 '19 at 11:06
  • 1
    Also you need to check `window.insertCSS === true` otherwise the code will fail on a page that has an element with an id "insertCSS" which creates an implicit global variable, both in the page context and in the content script. – wOxxOm May 07 '19 at 11:39