Google Chrome Extensions - Can't load local images with CSS

Viewed 57727

I have a simple Chrome extension that uses the content script feature to modify a website. More specifically, the background-image of said website.

For some reason I can't seem to be able to use local images, even though they are packed in the extension.

body {
    background: #000 url('image.jpg') !important;
    background-repeat: repeat !important;
}

That's it, the simplest CSS... but it won't work. The browser doesn't load the image.

10 Answers

Those answers above are great but your extension gets a new id every time it gets installed, so putting the id manually doesn't work if you gonna make it public at some point.

Here's my solution using manifest v.3:

//Get the url from some file within your extension's folder and store it on a global variable
var url = chrome.runtime.getURL('my_extension/img/Icon.svg');

//Take off the last part from the url string
url = url.replace('img/Icon.svg', '');

Now replace the src attribute for a custom one on every img tag and keep the file path as it's value like this:

<img ref-file="img/IconStop.svg" alt="">

Then run this function after loading the html:

loadImgs = function () {
    $("img[ref-file]").each(function() {
        var ref_file = $(this).attr('ref-file');
        url = url + ref_file;
        $(this).attr('src', url);
    });
}
Related