Chrome extension: insertCSS once per tab

蓝咒 提交于 2021-01-29 07:48:50

问题


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:


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


来源:https://stackoverflow.com/questions/56020244/chrome-extension-insertcss-once-per-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!