Reputation: 53930
I'm developing a "content script" Chrome extension. I'm trying to use a CSS files to style some existing elements on a page and to style elements that I create dynamically with JavaScript.
I've specified my CSS file in the manifest.json
file:
{
...
"content_scripts": [
{
"matches": [ ... ],
"js": [ ... ],
"css": [ "style.css" ]
}
]
...
}
And then if I put something like below into my style.css
nothing happens:
body {
background-color: red;
}
I've also put some rules in the form of:
#MyInsertedEl {
color: red;
}
And then inserted (using jQuery) a element with the id of MyInsertedEl
(anchor link) into the page but it's colour is not red (the element is inserted and visible in the page).
So what gives? What am I doing wrong? According to the docs I've got everything as I should, and google does not return anything useful.
edit: this code is run on facebook's pages if that is relevant in any way ...
Upvotes: 11
Views: 8955
Reputation: 15478
You need to have at least one stylesheet file included on your page in order to have your content_script
styles applied:
<link rel="stylesheet" type="text/css" href="#" />
So if you don't have any stylesheets included just add a blank link
tag like the above.
I know it sounds funny but it actually worked for me.
Two things are specific to my scenario
file
protocol.html
(in my case .md
)Q: Why do I need stylesheets on .md
files?
A: The content_script
matches on .md
files and inserts a js
file that compiles the markdown to html. The styles are for the generated html.
{
"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
}
]
}
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; }
file:///1.md
filescript.js
.md
file - initially the styles are loadedI understand that this is an edge case, but it's possible scenario for my extension and I just wanted to point out my solution.
Upvotes: 1
Reputation: 53930
Well, apparently, there's a bug in Chrome. If you have a ?
in your matches
expression CSS files will not be loaded. I've filed a bug report with more details here.
Upvotes: 11
Reputation: 111255
Is your javascript getting injected (match rule is correct)? Try adding !important
to your css rules:
color: red !important;
Upvotes: 1