Skip to content

Instantly share code, notes, and snippets.

@Northernside
Created January 26, 2021 16:21
Show Gist options
  • Save Northernside/dab6e72bcac1c304696a78919d19d93b to your computer and use it in GitHub Desktop.
Save Northernside/dab6e72bcac1c304696a78919d19d93b to your computer and use it in GitHub Desktop.
Simple Electron IPC messages transmitter and receiver
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<button id="test">Test</button>
<script src="./renderer.js"></script>
</body>
</html>
const {app, ipcMain, BrowserWindow} = require('electron');
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: __dirname + '/preload.js'
}
});
mainWindow.loadFile('index.html')
}
ipcMain.handle('example', () => { // If our code gets the 'example' message then do the following:
console.log('figgo');
});
app.whenReady().then(createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld('msg', {
'example': () => {
return ipcRenderer.invoke('example');
}
});
document.getElementById('test').addEventListener('click', () => {
if(window.msg) {
window.msg.example();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment