captainrad
captainrad

Reputation: 3830

Inject CSS conditionally via chrome extension options

I have a chrome extension with an options page that contains several check boxes for enabling or disabling certain CSS styles (on one specific matched URL).

Currently the checkbox true or false value is being stored in chrome.storage. There is no problem storing or retreiving the checkbox checked state.

My question is this: How can I, based on a checkboxes checked state, inject CSS into the specific page?

manifest.json

"permissions": [
  "storage",
  "tabs",
  "management",
  "https://www.some-specific-website/home/*"
]

Upvotes: 3

Views: 1730

Answers (1)

eholder0
eholder0

Reputation: 312

If you have configured your manifest properly, then your content script will only execute on matched pages. See here for details: https://developer.chrome.com/extensions/content_scripts

As for injecting CSS, it depends on what you want to do. You'll want to read from storage in the content script to get the state of your check box obviously, and if found then you need to inject.

Is what you're trying to inject fairly small? If so, it is probably best to just do it with a bit of JavaScript by selecting the elements you need in the Dom and adding a class to them with the properties you want to set. For what it is worth, adding a class is probably the most efficient way to change the CSS of some element rather than directly editing its style.

If it is fairly large, you can use the insertCSS method on a tab as you've mentioned. You'll need to add the tabs permission (I think it is called activeTab or something strange) to your manifest file. From there, get the current tab then call insertCSS with either raw CSS code or better yet, a file reference to your CSS file along with the id of the current tab to on which to apply it. See here for more info: https://developer.chrome.com/extensions/tabs#method-insertCSS

Also, there's a zip file with relevant example in the chrome extension samples page here: https://developer.chrome.com/extensions/examples/api/storage/stylizr.zip

Upvotes: 3

Related Questions