1.0.0 • Published 5 years ago

electron-static v1.0.0

Weekly downloads
4
License
ISC
Repository
github
Last release
5 years ago

electron-static

npm build

Local static files with MIME types for Electron apps

If you want to avoid bundling but nodeIntegration should be off, this can help. If you want to avoid bundling and content is local/offline, you can enable nodeIntegration and use Node's require().

This is one method of getting around the limitations of file:// protocol in Electron renderer processes. MIME types permit ES6 modules and a custom protocol enables history.pushState(). This is a proof of concept and the MIME type resolution is based only on file extension.

Usage

In your main process, create and attach the handler. The default directory is electron.app.getAppPath(), which becomes something like node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar when in development. Using __dirname will serve the same directory as main.js.

const {app, BrowserWindow, protocol} = require('electron');
const createStaticHandler = require('..');

const localHandler = createStaticHandler(__dirname);
protocol.registerStandardSchemes(['local'], {secure: true});

let mainWindow;
app.on('ready', async () => {
	protocol.registerBufferProtocol('local', localHandler, error => {
		if (error) {
			console.error('Failed to register protocol', error);
		}
	});

	mainWindow = new BrowserWindow();
	mainWindow.loadURL('local://-/');
	// URLs must have a placeholder host, like `-`
});

Partitions

Handle the protocol within certain partitions.

const session = partition ?
	electron.session.fromPartition(partition) :
	electron.session.defaultSession;

session.protocol.registerBufferProtocol('local', createStaticHandler());

Related