通过chrome扩展选项有条件地注入CSS [英] Inject CSS conditionally via chrome extension options

查看:286
本文介绍了通过chrome扩展选项有条件地注入CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有选项页的chrome扩展程序,其中包含多个复选框,用于启用或禁用某些CSS样式(在一个特定的匹配URL上).

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).

当前,复选框truefalse值存储在chrome.storage中.存储或获取复选框已选中状态没有问题.

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

我的问题是这样的: 如何基于复选框的选中状态将CSS注入特定页面?

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

manifest.json

manifest.json

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

推荐答案

如果正确配置了清单,则内容脚本将仅在匹配的页面上执行.详情请参阅此处: https://developer.chrome.com/extensions/content_scripts

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

对于注入CSS,这取决于您要执行的操作.您需要从内容脚本中的存储中读取内容,以明显了解复选框的状态,如果找到该复选框,则需要注入.

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.

您要注入的东西很小吗?如果是这样,最好通过使用一些JavaScript来做到这一点,方法是在Dom中选择所需的元素,然后使用要设置的属性向它们添加一个类.就其价值而言,添加类可能是更改某些元素的CSS而不是直接编辑其样式的最有效方法.

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.

如果它很大,您可以如上所述在选项卡上使用insertCSS方法.您需要在清单文件中添加tabs权限(我认为它称为activeTab或其他奇怪的东西).从那里,获取当前选项卡,然后使用原始CSS代码或更高级的CSS代码调用insertCSS,该文件是对CSS文件的文件引用以及当前选项卡的ID(要在其上应用该ID).详情请参阅此处: https://developer.chrome.com/extensions/tabs#method -insertCSS

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

此外,在chrome扩展示例页面中,还有一个带有相关示例的zip文件: https://developer.chrome.com/extensions/examples/api/storage /stylizr.zip

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扩展选项有条件地注入CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆