Created
August 20, 2018 00:36
-
-
Save GoodNovember/79ff7272af65086ab640d31a9bf868db to your computer and use it in GitHub Desktop.
Sending data between window instances with Electron.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { ipcRenderer } = require('electron') | |
ipcRenderer.on('postal-error',(event, errorPayload)=>{ | |
const { | |
error, | |
sender, | |
destination, | |
payload | |
} = errorPayload | |
console.error('[Postal Error]', errorPayload) | |
}) | |
// Let's get cute. | |
const hiYouCanCallMe = (sender) => { | |
ipcRenderer.send('register-letter-address', sender) | |
return (destination) => (payload) => ipcRenderer.send('send-letter', {sender,destination,payload}) | |
} | |
const whenALetterArrivesFrom = (sender) => (callback) => ipcRenderer.on('letter-from-${sender}', callback) | |
// Now, I think I'll call this intance Alice. | |
const sendLettersTo = hiYouCanCallMe('Alice') | |
// Rachael has a friend named Alice, another window instance. | |
const sendLetterToRachael = sendLettersTo('Rachael') | |
// Yay! | |
sendToRachael({ | |
title:"Hello! Long time no see!", | |
body:"It has been over three years since the shipwreck, but..." | |
}) | |
// We like this person | |
const whenFromRachael = whenALetterArrivesFrom('Rachael') | |
whenFromRachael((event, payload)=>{ | |
/* | |
read() | |
reply() | |
keepForLater() | |
*/ | |
}) | |
// We don't like this person. | |
const burnInABonfire = (event, payload) => {} | |
const whenFromJames = whenALetterArrivesFrom('James') | |
whenFromJames(burnInABonfire) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {ipcMain} = require('electron') | |
ipcMain.on('register-letter-address', ( event, { name })=>{ AddressMap.set(name,event.sender) }) | |
ipcMain.on('send-letter',(event, { sender, destination, payload })=>{ | |
if(AddressMap.has(destination)){ | |
destination.send(`letter-from-${sender}`, payload) | |
}else{ | |
event.sender.send(`postal-error`,{ | |
error:'unknown-destination', | |
destination, | |
sender, | |
payload | |
}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment