I am new to electron and trying to load images from the local file system to display it on screen. So for images from the remote URLs are working just fine when I do
<img src='https://example.com/image.jpg' />
But when I try to load the same image from the local file system in my render process it does not work
<img src='file:///C:/tmp/image.jpg' />
is not rendered.
This is the error I got:
> Not allowed to load local resource:
> file:///C:/tmp/nW4jY0CHsepy08J9CkF1u3CJVfi4Yvzl_screenshot.png
> dashboard:1 Not allowed to load local resource:
> file:///C:/tmp/TOyUYWnJK7VS9wWeyABhdgCNmp38FyHt_screenshot.png
Is there any configuration that needs to be made to allow the electron to render images from the local file system Or I am doing it entirely wrong?
Electron by default allows local resources to be accessed by render processes only when their html files are loaded from local sources with the file://
protocol for security reasons.
If you are loading the html from any http://
or https://
protocol even from a local server like webpack-dev-server, access to local resources is disabled.
If you loading html pages from a local server only during development and switching to local html files in production, you can disable websecurity during development, taking care to enable it in production.
If you are loading html from remote sources even in production, the best and secure way is to upload it somewhere on your server and load it.
Method 1. Implement protocol.interceptFileProtocol with scheme 'file'.
Call callback with the file's directory path
Method 2. Implement session.defaultSession.webRequest.onBeforeRequest with a filter on 'file:///'.
In the callback load the file via node, convert to Base64 and return that.
Elaborating on Method 1:
protocol.interceptFileProtocol('resource', (req: ProtocolRequest, callback: (filePath: string) => void) => {
if (someCondition) {
const url = GetSomeFilePath(req.url);
callback(url);
}
else {
callback(req.url);
}
});
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