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

前端 未结 1 1912
旧巷少年郎
旧巷少年郎 2021-01-16 21:47

When a user clicks on the browser icon for the extension, it brings up the Popup that has been defined.

I need to create a toggle button to turn on/off a stylesheet

相关标签:
1条回答
  • 2021-01-16 22:26

    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.

    0 讨论(0)
提交回复
热议问题