Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron JS Images from Local File System

Tags:

electron

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

enter image description here

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?

like image 475
Aftab Naveed Avatar asked May 10 '18 11:05

Aftab Naveed


2 Answers

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.

like image 185
quantumkv Avatar answered Oct 31 '22 10:10

quantumkv


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);

            }            

        }); 
like image 22
J. Reynolds Avatar answered Oct 31 '22 11:10

J. Reynolds