简体   繁体   English

通过chrome扩展选项有条件地注入CSS

[英]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). 我有一个带有选项页的chrome扩展程序,其中包含几个复选框,用于启用或禁用某些CSS样式(在一个特定的匹配URL上)。

Currently the checkbox true or false value is being stored in chrome.storage . 当前,复选框truefalse值存储在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? 我的问题是:如何根据复选框的选中状态将CSS注入特定页面?

manifest.json 的manifest.json

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

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 详情请参阅此处: https//developer.chrome.com/extensions/content_scripts

As for injecting CSS, it depends on what you want to do. 至于注入CSS,取决于您要执行的操作。 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. 如果是这样,最好通过使用一些JavaScript来做到这一点,方法是在Dom中选择所需的元素,然后使用要设置的属性向它们添加一个类。 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. 就其价值而言,添加类可能是更改某些元素的CSS而不是直接编辑其样式的最有效方法。

If it is fairly large, you can use the insertCSS method on a tab as you've mentioned. 如果它很大,您可以如上所述在选项卡上使用insertCSS方法。 You'll need to add the tabs permission (I think it is called activeTab or something strange) to your manifest file. 您需要在清单文件中添加tabs权限(我认为它称为activeTab或其他奇怪的东西)。 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. 从那里,获取当前选项卡,然后使用原始CSS代码或更高级的CSS代码调用insertCSS,该文件是对CSS文件的文件引用以及当前选项卡的ID(将其应用于其)。 See here for more info: https://developer.chrome.com/extensions/tabs#method-insertCSS 请参阅此处以获取更多信息: 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 另外,这里的chrome扩展示例页面中有一个包含相关示例的zip文件: https : //developer.chrome.com/extensions/examples/api/storage/stylizr.zip

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM