Skip to content

Instantly share code, notes, and snippets.

@erickzhao
Last active October 6, 2020 05:05
Show Gist options
  • Select an option

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

Select an option

Save erickzhao/b54e99f90634aad550a6a2586d4751f9 to your computer and use it in GitHub Desktop.
Baby's first context bridge
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" type="text/css" href="./styles.css">
</head>
<body>
<script src="./renderer.js"></script>
</body>
</html>
// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path');
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
ipcMain.on('erick', (_event, args) => {
console.log('ARGS SENT FROM RENDERER:', args);
})
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld(
'electron',
{
ipcSend: (channel, ...args) => ipcRenderer.send(channel, args)
}
)
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
window.electron.ipcSend('erick', 'was', 'here');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment