【问题标题】:My CSS is not getting injected through my content script我的 CSS 没有通过我的内容脚本注入
【发布时间】:2012-04-01 01:21:02
【问题描述】:

谁能给我解释一下。我正在尝试使用带有 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
    }
  ]
}

myStyles.css

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

【问题讨论】:

    标签: css google-chrome-extension content-script


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      1. 增加 CSS 规则的 specificity
      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"]
        }
        

        manifest version 2 处于活动状态时,最后一个键web_accessible_resources 是必需的,以便可以从非扩展页面读取CSS 文件。

      【讨论】:

      • 澄清:您确实不必必须同时使用这两种方法。使用其中一个就可以了。第一个更可靠,第二个可能会导致闪烁。
      • #1 对我有用,但#2 不起作用。这真的很奇怪。原始页面是否有可能试图阻止扩展以更改其样式?在某些网站(例如,appannie.com)上可以,但有些则不行(例如,facebook.com)。无论如何,#1很棒。谢谢!
      • @Xan 它成为文档中的最后一个样式表,因此如果特异性至少与文档中现有样式表一样高,则注入的样式表优先。
      猜你喜欢
      • 2013-07-02
      • 2014-01-10
      • 2023-03-17
      • 2011-11-22
      • 1970-01-01
      • 2013-02-01
      • 2014-11-03
      • 1970-01-01
      相关资源
      最近更新 更多