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