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
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.