I'm building a Chrome extension, and am trying to add a div with a background image to the DOM via a content script. The CSS loads in correctly, and the image URL seems to be correct looking at it via the Developer Tools inspector.
$('.close-button').css('background', 'url('+chrome.extension.getURL('img/btn_close.png')+')');
The URL shows up in the inspector as
chrome-extension://fdghianmcdbcgihapgdbjkdoaaocmoco/img/btn_close.png
But the image does not load in the background. If I do the same thing, but load the image as the src of an img tag, the image plainly shows as broken in the browser.
However, when I paste this URL into the browser URL bar and load it, it shows up fine. What's the problem loading it into the DOM?
I found the answer in the chrome extension docs. By default, files in the extension root are not accessible in the web page DOM. The developer can override this with the "web_accessible_resources" setting in the manifest.json file:
http://code.google.com/chrome/extensions/manifest.html#web_accessible_resources
{
...
"web_accessible_resources": [
"images/my-awesome-image1.png",
"images/my-amazing-icon1.png",
"style/double-rainbow.css",
"script/double-rainbow.js"
],
...
}
Special shout-out as well to Matt Greer's comment suggesting using a data url, which I believe also works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With