Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Chrome Extension Images Show Up As Broken When Added to the DOM?

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?

like image 497
Travis Avatar asked Dec 21 '25 05:12

Travis


1 Answers

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.

like image 161
Travis Avatar answered Dec 22 '25 19:12

Travis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!