3

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/*"
]
captainrad
  • 3,760
  • 16
  • 41
  • 74
  • Tried adding `style` element to document ? – guest271314 Jan 29 '16 at 19:18
  • How would I do that when I only want it to happen on the matched url? – captainrad Jan 29 '16 at 19:19
  • _"Currently the checkbox true or false value is being stored in chrome.storage. There is no problem storing or retreiving the checkbox checked state."_ Check for `location.href` at `onchange` event of checkbox ? – guest271314 Jan 29 '16 at 19:21
  • I think that is the wrong approach when developing a chrome extension. Unless you can correct me. From what I've read on the chrome extension docs, you should use "chrome.tabs.insertCSS". The problem is that I don't know how to do so conditionally based on content_scripts. – captainrad Jan 29 '16 at 19:23
  • Not tried `chrome.tabs.insertCSS` , fwiw previous attempt at adjusting `css` at `html` document http://github.com/guest271314/toggleStyles-chromium-extension – guest271314 Jan 29 '16 at 19:45

1 Answers1

3

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

eholder0
  • 302
  • 3
  • 15