0
votes

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.

1
See Chrome extension: Checking if content script has been injected or not - you can even simplify it by using an embedded code instead of file. - wOxxOm
Thanks, @wOxxOm. I don't know why I didn't find that thread, but this is exactly what I need! - RoelN

1 Answers

0
votes

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'});
        }
    });
}