Sarbbottam
Sarbbottam

Reputation: 5580

Enable/Disable "content_scripts.css" in Chrome Extension

For example:

  ...
  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "css": ["style.css"]
    }
  ]
  ...

I would like to inject this stylesheet by default. Which is business as usual.

I would also like to enable/disable, when the user when the user clicks on the icon in the toolbar.

Any pointer would be helpful. Thanks!

Upvotes: 3

Views: 1426

Answers (2)

happynow
happynow

Reputation: 7

This is my workaround.

manifest.json

...
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content_script.js"]
  }
],
"web_accessible_resources": [
  "my_style.css"
]
...

content_script.js

const target = document.head || document.documentElement;

const link  = document.createElement('link');
link.id = 'my_style_css';
link.rel  = 'stylesheet';
link.type = 'text/css';
link.href = chrome.runtime.getURL('my_style.css');

target.appendChild(link);

to disable

link.disabled = true;

//or

document.getElementById('my_style_css').disabled = true;

Upvotes: 0

Noam Hacker
Noam Hacker

Reputation: 4835

I had to implement this in one of my extensions as well. I used a checkbox in my popup.html to manipulate chrome.storage, which would store whether the state was enabled or disabled.

The content script was always running, but would check chrome.storage first before performing any actions. Feel free to refer to my repository here, particularly inject.js.

This isn't the only way to do it, but it was pretty simple for me to implement. Note that you can't use localstorage because the content script exists in a separate environment.

Upvotes: 1

Related Questions