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.
Your image URL should look like
chrome-extension://<EXTENSION_ID>/image.jpg
You would be better off replacing css through javascript. From docs:
There are a lot of older answers and solutions to this question.
As of August 2015 (using Chrome 45 and Manifest version 2), the current "best practice" for linking to local images within Chrome Extensions is the following approach.
1) Link to the asset in your CSS using a relative path to your extension's images folder:
2) Add the individual asset to to the web_accessible_resources section of your extension's manifest.json file:
Note: This method is suitable for a few files, but doesn't scale well with many files.
Instead, a better method is to leverage Chrome's support for match patterns to whitelist all files within a given directory:
Using this approach will allow you to quickly and effortlessly use images in your Chrome Extension's CSS file using natively supported methods.
My solution.
With Menifest v2 you need to add
web_accessible_resources
to the file and then usechrome-extension://__MSG_@@extension_id__/images/pattern.png
as the url in your css file.CSS:
Manifest.json
p.s. Your manifest.json might look different to this one.
This CSS-version-only works in extension environment (app page, popup page, background page, option page) as well as content_scripts CSS file.
In .less file, I always set a variable at the beginning:
Then later, if you want to refer to extension-local-resource like images, use:
If you want to test local image on the live site you can run local web server and set URL like http://127.0.0.1:8123/img.jpg on page using DevTools
There is different ways to run a web server:
Extension for browser "Web Server for Chrome" with defined folder https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb
If you have python then run embedded http server at chosen folder
python3 -m http.server 8123 # python 3 version
python -m SimpleHTTPServer 8123 # python 2 version
Use production ready server like nginx, apache
Also I tried chrome launching flag --allow-file-access-from-files but it wasn't work for my version 52.0.2743.116 and it's dangerous and insecure. Documents originating from anywhere, local or web, shouldn't, by default, have any access to local file:/// resources.
Chrome has i18n support that provides the ability to reference your extension in your CSS. I keep my images in an image folder in the extension, so reference assets in the CSS like so: