How to dynamically modify the manifest file css file for Chrome Extension, or what is the correct way to toggle a stylesheet on/off?

淺唱寂寞╮ 提交于 2020-01-06 09:31:21

问题


Branching off my Other Question, a user successfully got me to serve a stylesheet but that is the wrong way; it is not what I needed to do.

So I have come up with a more accurate question:

Basically, you can make an extension permanently modify a web page by defining a content script in manifest.json.

I need the ability to, on the click of a button within popup.html, toggle a stylesheet on or off.

The answer to my other question I linked to, only allows my to serve a stylesheet, but that is removed again as soon as the page is reloaded.

I want to basically set the option for the extension to permenantly turn on a stylesheet for a web page, or to turn it off, by clicking the toggle button located in the browser icon popup.html.

See the screenshot:



I think what I need is for the button to change a setting in the extension which will either turn on or turn off a css stylesheet content script, or swap with a different css stylesheet content script.

I hope I have made this clear enough to understand.


回答1:


Why do you want to re-invent the wheel?

Have a look at Stylish for Chrome, a UserScript manager (originated from Stylish for Firefox).

If you still want to continue development of such an extension, the following methods can be used, on top of the one I described in my previous answer:

  1. chrome.tabs.onUpdated - Detect tab state changes (place this code in your background page):

    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        chrome.tabs.executeScript(tab.id, {code:
           'document.documentElement.setAttribute("RWchooseStyle", "style1.css");'
        });
        // myscript.js defined in https://stackoverflow.com/a/9647059
        chrome.tabs.executeScript(tab.id, {file: 'myscript.js'});
    });
    
  2. localStorage - For persistence (so that preferences can be "remembered" in your extension):
    localStorage.getItem('name') to retrieve preferences, localStorage.setItem('name','value') to set preferences.

    Only strings can be remembered, so string = JSON.stringify(some_variable) and original_variable = JSON.parse(string) can be used in order to save numbers, arrays and other primitives.



来源:https://stackoverflow.com/questions/9648140/how-to-dynamically-modify-the-manifest-file-css-file-for-chrome-extension-or-wh

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