Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jarek-foksa
Forked from SMotaal/README.md
Last active July 7, 2020 13:42
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jarek-foksa/0f6e82bdaf8fb1962c9e14035a8725e4 to your computer and use it in GitHub Desktop.
Save jarek-foksa/0f6e82bdaf8fb1962c9e14035a8725e4 to your computer and use it in GitHub Desktop.
Electron 2.x demo app that demonstrates how to enable ES modules support.
<!DOCTYPE html>
<html>
<head>
<base href="app://./" />
<meta http-equiv="Content-Security-Policy" content="script-src 'self' app:; object-src 'self' app:;">
<script type="module" src="./module.js"></script>
</head>
<body>
Check the console!
</body>
</html>
let {app, protocol, BrowserWindow} = require("electron");
let {readFile} = require("fs");
let {extname} = require("path");
let {URL} = require("url");
let createProtocol = (scheme, normalize = true) => {
protocol.registerBufferProtocol(scheme,
(request, respond) => {
let pathName = new URL(request.url).pathname;
pathName = decodeURI(pathName); // Needed in case URL contains spaces
readFile(__dirname + "/" + pathName, (error, data) => {
let extension = extname(pathName).toLowerCase();
let mimeType = "";
if (extension === ".js") {
mimeType = "text/javascript";
}
else if (extension === ".html") {
mimeType = "text/html";
}
else if (extension === ".css") {
mimeType = "text/css";
}
else if (extension === ".svg" || extension === ".svgz") {
mimeType = "image/svg+xml";
}
else if (extension === ".json") {
mimeType = "application/json";
}
respond({mimeType, data});
});
},
(error) => {
if (error) {
console.error(`Failed to register ${scheme} protocol`, error);
}
}
);
}
// Standard scheme must be registered before the app is ready
protocol.registerStandardSchemes(["app"], { secure: true });
app.on("ready", () => {
createProtocol("app");
let browserWindow = new BrowserWindow({webPreferences: {preload: `${__dirname}/preload.js`}});
browserWindow.webContents.openDevTools();
browserWindow.loadFile("index.html");
});
console.log("ES module loaded");
{
"name": "demo",
"version": "1.0.0",
"main": "main.js"
}
let {webFrame} = require("electron");
process.once("loaded", () => {
// Allow window.fetch() to access app files
webFrame.registerURLSchemeAsPrivileged("app", {
secure: true,
bypassCSP: false,
allowServiceWorkers: true,
supportFetchAPI: true,
corsEnabled: false
});
});
@erikparr
Copy link

thank you for this! very helpful.

@jcc10
Copy link

jcc10 commented Jan 7, 2019

This combined with what it was forked from allowed me to make my app work. Thanks!

@anderejd
Copy link

anderejd commented Apr 9, 2019

Thank you so much for this gist! I'm just trying Electron for the first time and did some WebAssembly experiments with it here: https://github.com/anderejd/electron-wasm-rust-example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment