I'm trying to write a Chrome Extension that just adds a CSS file to the end of a page's css definitions.
Google's documentation says that I can just use the function chrome.tabs.insertCSS()
to add css to a page, but running it from a content_script
included javascript file does nothing.
I'm trying two separate methods as documented on Google's site. I have an alert()
statement to tell me where in the script I am, but it never runs the final alert
. This makes me think that my script may be crashing somewhere in the middle.
Here are my source files:
manifest.json
{
"name": "Custom CSS to GOOGLE",
"version": "1.0",
"description": "The first extension that I made.",
"content_scripts": [
{
"matches": ["http://*/*"],
//"js": ["style_injector.js"],
"js": ["inject.js"],
"css": ["newstyle.css"]
}
],
"permissions": [
"tabs", "http://*/*"
]
}
inject.css
alert("newpage");
chrome.tabs.executeScript(null, {code:"document.body.bgColor='red'"});
chrome.ta开发者_JAVA技巧bs.insertCSS(
null,
{
code:"body{background:red;}"
}
);
alert("finishpage");
You can't call chrome.tabs.*
API from a content script. You need to do it from a background page. If you need to communicate between a content script and a background page there is message passing available.
PS. Things like "This makes me think that my script may be crashing somewhere in the middle." could be easily checked by looking at the console (for content scripts it is just a regular console in a tab, Ctrl+J
).
"I'm trying to write a Chrome Extension that just adds a CSS file to the end of a page's css definitions"
You might need to add the !important
flag to the css you are changing:
When the browser is displaying an HTTP page and the user clicks this extension's browser action, the extension sets the page's bgcolor property to 'red'. The result, unless the page has CSS that sets the background color, is that the page turns red.
...the !important
flag is the only way to change some things but you may have to write js to override other styles, check this
As serg said, the background.html page is where you use the injectCSS api:
/* in background.html */
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null,
{code:"document.body.bgColor='red'"});
});
/*in manifest.json */
"permissions": [
"tabs", "http://\*/*"
],
精彩评论