Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
Roman Avatar asked Jul 19 '12 03:07

Roman


People also ask

How do I add CSS extensions to Chrome?

Once the manifest, CSS and JavaScript files are ready, head over to chrome://extensions/ from the browser's address bar and enable developer mode. That activates the “Load unpacked” button to add the extension files. It's also possible to toggle whether or not the developer version of the extension is active.

How do I run CSS in Chrome?

Press Ctrl + Shift + i for Windows/Linux (or command + option + i for Mac). Right-click on an element on your website page and select Inspect. Now that you are familiar with accessing Google Chrome Developer Tools, you will be able to inspect CSS elements to modify them live.

How do I inject JavaScript to Chrome extension?

To run a script: - Open the extension and click the play button. Or - Run a script from the context menu. Right Click > Select Scripty > Select your script.


1 Answers

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.

like image 88
Brock Adams Avatar answered Oct 09 '22 08:10

Brock Adams