20

谁能给我解释一下。我正在尝试使用带有 Google 扩展的 content_script 将 CSS 文件注入网页,但我的 css 文件从未添加到网页中。有人可以告诉我我做错了什么并帮助我解决它吗?谢谢

显现:

{
  "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
    }
  ]
}

我的样式.css

#test {
    margin: 0 10px;
    background: #fff;
    padding: 3px;
    color: #000;
}
4

2 回答 2

52

样式表实际上是注入的,但没有应用,因为其他样式会覆盖规则。要使规则生效,您有一些选择:

  1. 增加 CSS 规则的特异性
  2. 为每条规则添加后缀!important

    #test {
        margin: 0 10px !important;
        background: #fff !important;
        padding: 3px !important;
        color: #000 !important;
    }
    
  3. 通过内容脚本注入 CSS:

    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清单版本2 处于活动状态时是必需的,以便可以从非扩展页面读取 CSS 文件。

于 2012-03-15T14:16:12.327 回答
1

如果您想定位特定网站,请执行以下操作:

"matches": ["https://*.google.com/*"]

//*以前对我.google来说是真正的窍门,因为使用www不起作用。

于 2020-07-06T17:16:27.900 回答