代码之家  ›  专栏  ›  技术社区  ›  Jan Hančič

Chrome扩展的CSS未加载

  •  9
  • Jan Hančič  · 技术社区  · 15 年前

    我正在开发一个“内容脚本”Chrome扩展。我尝试使用CSS文件来设置页面上一些现有元素的样式,以及使用JavaScript动态创建的元素的样式。

    我已经在 manifest.json

    {
        ...
        "content_scripts": [
            {
                "matches": [ ... ],
                "js": [ ... ],
                "css": [ "style.css" ]
            }
        ]
        ...
    }
    

    style.css 什么也没发生:

    body {
        background-color: red;
    }
    

    我还制定了一些规则:

    #MyInsertedEl {
        color: red;
    }
    

    然后插入(使用jQuery)id为的元素 MyInsertedEl (锚链接)进入页面,但其颜色不是红色(元素被插入并在页面中可见)。

    编辑:这段代码运行在facebook的页面上,如果这与任何方式相关。。。

    3 回复  |  直到 15 年前
        1
  •  10
  •   Jan Hančič    15 年前

    嗯,很明显,Chrome有个bug。如果你有 ? 在你的 matches 不会加载expression CSS文件。我已经提交了一份错误报告,里面有更多细节 here .

        2
  •  1
  •   serg    15 年前

    你的javascript被注入了吗(匹配规则是正确的)?尝试添加 !important 对于您的css规则:

    color: red !important;
    
        3
  •  1
  •   simo    12 年前

    参见下面的编辑

    您需要在页面中至少包含一个样式表文件,以便 content_script

    <link rel="stylesheet" type="text/css" href="#" />
    

    因此,如果没有包含任何样式表,只需添加一个空白 link 像上面这样标记。

    我知道这听起来很有趣,但实际上对我有用。

    编辑

    有两件事是针对我的情况的

    1. 错误仅发生在 file 协议
    2. .html (就我而言 .md

    问: .医学博士 文件夹?

    这个 匹配 .医学博士 文件和插入 js

    manifest.json文件

    {
        "manifest_version": 2,
        "name"            : "bug",
        "version"         : "1.0",
        "description"     : "bug",
    
        "content_scripts": [
            {
                "matches": [
                    "*://*/*.*",
                    "file:///*/*.*"
                ],
                "css": ["style.css"],
                "js": ["script.js"],
                "run_at": "document_start",
                "all_frames": true
            }
        ]
    }
    

    脚本.js

    window.addEventListener('load', function (e) {
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = '#';
        document.head.appendChild(link);
    }, false);
    

    body { background: gray; }
    

    台阶

    1. file:///1.md 文件
    2. 注释掉里面的代码 script.js
    3. .医学博士 文件-最初加载样式