For a Google Chrome extension, how do I define a stylesheet toggle within the Popup?

让人想犯罪 __ 提交于 2019-12-01 14:57:30

You can use the chrome.tabs.executeScript method to dynamically inject/remove CSS (requires the tabs permission in manifest.json):

chrome.tabs.executeScript(null, {code:
    'document.documentElement.setAttribute("RWchooseStyle", "style1.css");'
}, function() {
    chrome.tabs.executeScript(null, {file: 'myscript.js'});
});

In myscript.js, detect whether you have already inserted CSS. If not, add a new <style> or link element, and assign an id to it. Otherwise, replace the style sheet.

Example of myscript.js:

var selectedStyle = document.documentElement.getAttribute('RWchooseStyle');
var id, link;
if (selectedStyle) {
    id = 'RW_style_' + selectedStyle.replace(/\W/g,'');   // Sanitize id
    // Remove previous sheet, if available.
    link = document.getElementById(id);
    if (link) {
        link.parentNode.removeChild(link);
    }
}
if (id) {
    // Insert new sheet
    link = document.createElement('link');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = chrome.extension.getURL(selectedStyle);
    link.id = id;
    (document.head||document.documentElement).appendChild(link);
}

// Remove temporary attribute
document.documentElement.removeAttribute('RWChooseStyle');

In this example, the CSS files have to be defined in your extensions directory. Of course, you can also use <style> instead if <link>, and dynamically set the style's content.

Note: Do not forget to add the style sheet to the web_accessible_resources section of the manifest file.

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