Google Chrome Extensions - Can't load local im

2019-01-03 21:43发布

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.

9条回答
Fickle 薄情
2楼-- · 2019-01-03 22:27

One option would be to convert your image to base64:

and then put the data right into your css like:

body { background-image: url(data:image/png;base64,iVB...); }

While this might not be an approach you would want to use when regularly developing a webpage, it is a great option due to some of the constraints of building a Chrome Extension.

查看更多
等我变得足够好
3楼-- · 2019-01-03 22:27

Just to clarify, according to the documentation, every file in an extension is also accessible by an absolute URL like this:

chrome-extension://<extensionID>/<pathToFile>

Note the <extensionID> is a unique identifier that the extension system generates for each extension. You can see the IDs for all your loaded extensions by going to the URL chrome://extensions. The <pathToFile> is the location of the file under the extension's top folder; it's the same as the relative URL.

...

Changing background image in CSS:

#id { background-image: url("chrome-extension://<extensionID>/<pathToFile>"); }


Changing background image in CSS through JavaScript:

document.getElementById('id').style.backgroundImage = "url('chrome-extension://<extensionID>/<pathToFile>')");


Changing background image in CSS through jQuery:

$("#id").css("background-image", "url('chrome-extension://<extensionID>/<pathToFile>')");

查看更多
迷人小祖宗
4楼-- · 2019-01-03 22:31

One thing to mention is that in the web_accessible_resources you can use wildcards. So instead of

"images/pattern.png"

You can use

"images/*"

查看更多
登录 后发表回答