Electron JS Images from Local File System

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

            }            

        }); 

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.

Tags:

Electron