Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

javascript - How to inject CSS using content script file in Chrome extension?

I'm trying to inject my CSS from JavaScript which is injected as content script:

"content_scripts": [
   {
      "matches": ["http://www.google.com/*"],
      "js": ["script.js"]
   }
],

I found similar question about injecting CSS, but I encountered a problem while using code from accepted answer. Here's my script.js contents:

var link = document.createElement("link");
link.href = chrome.extension.getURL("style.css");
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);

After I load some page this message appears in console:

Denying load of chrome-extension://phkgaaiaakklogbhkdnpjncedlbamani/fix.css. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Is there any way to fix this? Or, maybe, some other way to inject a CSS from that JavaScript file?

Note: I can't include style sheet directly from manifest.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could add to the manifest's permissions field; See web_accessible_resources. So you would add this to the manifest:

    , "web_accessible_resources": [
        "fix.css"
    ]

See also "Programmatic injection". and insertCSS().

For most applications, forget all that createElement code and just add the CSS file to the manifest:

"content_scripts": [
   {
      "matches":    ["http://www.google.com/*"],
      "css":        ["fix.css"],
      "js":         ["script.js"]
   }
],

although I understand that you don't want to do that in this exact instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...