As for the Google Chrome extension, how can I change the style of the table in the popup?

When a user clicks on the browser icon to expand, it displays a popup that has been defined.

I need to create a toggle button to enable / disable the stylesheet for a specific page / domain when the user clicks the button inside the popup.

For example, when a user uses the Adblock extension, when the user clicks the browser icon, he brings up a pop-up window with a series of links. One of these links does not start on this page, which then changes to enable, which the user can click to enable it.

Another example (a much better example): the classic pop-up blocker has a button in the pop-up window that says: "add this page to the black list" and once clicked the change "remove from the black list".

The classic pop-up blocker is usually the functionality I want for my extension (it does nothing with ads or pop-up blockers, this is just an example), so when a user clicks a button in a pop-up window, he will turn the stylesheet turned on or off, which I wrote and saved as a .css file in the extension.

Hope I made it clear enough to understand.


SCREENS

Here is the photoshop I did so that you can see exactly what I'm trying to do:

photoshopped screenshot toggle on


and take a picture again to find out what should happen after pressing the buttons:

photoshopped screenshot toggle off


0
source share
1 answer

You can use the chrome.tabs.executeScript method to dynamically inject / remove CSS (requires 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 determine if you have already pasted CSS. If not, add a new <style> or link element and give it an id . Otherwise, replace the stylesheet.

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, CSS files must be defined in your extensions directory. Of course, you can also use <style> instead of <link> and dynamically set the style contents.

Note. Remember to add the stylesheet to the web_accessible_resources section of the web_accessible_resources file.

+1
source

Source: https://habr.com/ru/post/912116/


All Articles