我的 CSS 没有通过我的内容脚本注入 [英] My CSS is not getting injected through my content script
问题描述
谁能给我解释一下.我正在尝试使用带有 Google 扩展的 content_script 将 CSS 文件注入网页,但我的 css 文件从未添加到网页中.有人可以告诉我我做错了什么并帮助我修复它吗?谢谢
Can anyone explain this to me. I'm trying to inject a CSS file onto a webpage using the content_script with Google extensions, but my css file never gets added to the webpage. Can someone tell me what I'm doing wrong and help me fix it? thanks
清单:
{
"name": "Extension",
"version": "0",
"description": "",
"permissions": ["tabs", "http://*/*", "https://*/*", "file:///*/*"],
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*", "file:///*/*"],
"css": ["myStyles.css"],
"js": ["myScript.js"],
"all_frames": true
}
]
}
myStyles.css
myStyles.css
#test {
margin: 0 10px;
background: #fff;
padding: 3px;
color: #000;
}
推荐答案
实际上注入了样式表,但并未应用,因为其他样式会覆盖规则.要使规则生效,您有一些选择:
The style sheet is actually injected, but not applied, because other styles override the rules. To get the rules to work, you have some options:
- 增加 CSS 规则的具体性.
为每条规则添加
!important
后缀:
#test {
margin: 0 10px !important;
background: #fff !important;
padding: 3px !important;
color: #000 !important;
}
通过内容脚本注入 CSS:
Inject the CSS via a content script:
myScript.js
:
var style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = chrome.extension.getURL('myStyles.css');
(document.head||document.documentElement).appendChild(style);
manifest.json
{
"name": "Extension",
"version": "0",
"description": "",
"manifest_version": 2,
"permissions": ["tabs", "http://*/*", "https://*/*", "file:///*/*"],
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*", "file:///*/*"],
"js": ["myScript.js"],
"all_frames": true
}
],
"web_accessible_resources": ["myStyles.css"]
}
最后一个键,web_accessible_resources
在 manifest version 2 处于活动状态,以便可以从非扩展页面读取 CSS 文件.
The last key, web_accessible_resources
is necessary when manifest version 2 is active, so that the CSS file can be read from a non-extension page.
这篇关于我的 CSS 没有通过我的内容脚本注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!