问题
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