2012-03-15 27 views
14

任何人都可以向我解释这一点。我试图使用带有Google扩展名的content_script将一个CSS文件注入到网页上,但是我的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; 
} 

回答

31

样式表实际上是被注入,但不适用,因为其他样式覆盖的规则。要使规则起作用,您可以选择:

  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文件。

+3

澄清:你不**必须使用这两种方法。使用其中之一将会很好。第一个更可靠,第二个*可能会导致闪烁。 – 2012-03-15 14:22:23

+0

谢谢,它添加在:) – user1255276 2012-03-15 14:56:51

+0

#1适合我,但#2不工作。这真的很奇怪。原始页面是否有可能阻止扩展程序改变其风格?在一些网站上(例如,appannie.com)没关系,但有些网站不是(例如facebook.com)。无论如何,#1是伟大的。谢谢! – 2013-09-30 08:11:01

相关问题