Skip to content

Instantly share code, notes, and snippets.

@erickzhao
Last active October 14, 2020 04:29
Show Gist options
  • Select an option

  • Save erickzhao/d7cf98d8696c0c27940ff23e2f8f2e7e to your computer and use it in GitHub Desktop.

Select an option

Save erickzhao/d7cf98d8696c0c27940ff23e2f8f2e7e to your computer and use it in GitHub Desktop.
Electron Fiddle Gist
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Title</title>
</head>
<body>
<script src="./renderer.js"></script>
</body>
</html>
const {
app,
BrowserWindow,
ipcMain
} = require("electron");
const path = require("path");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: true, // protect against prototype pollution
preload: path.join(__dirname, "preload.js") // use a preload script
}
});
// Load app
win.loadFile(path.join(__dirname, "index.html"));
// rest of code..
}
app.on("ready", createWindow);
ipcMain.on("toMain", (_event, args) => {
win.webContents.send("fromMain", args);
});
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (data) => { ipcRenderer.send("toMain", data) },
receive: (handler) => {
ipcRenderer.on("fromMain", (_event, ...args) => handler(...args));
}
}
);
window.api.receive((data) => {
console.info(`Received ${data} from main process`);
});
window.api.send("Hello From contextBridge");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment