diff --git a/docs/fiddles/communication/two-processes/asynchronous-messages/index.html b/docs/fiddles/communication/two-processes/asynchronous-messages/index.html new file mode 100644 index 000000000000..43d23a29087f --- /dev/null +++ b/docs/fiddles/communication/two-processes/asynchronous-messages/index.html @@ -0,0 +1,27 @@ + + + + + + +
+
+

Asynchronous messages

+ Supports: Win, macOS, Linux | Process: Both +
+
+ + +
+

Using ipc to send messages between processes asynchronously is the preferred method since it will return when finished without blocking other operations in the same process.

+ +

This example sends a "ping" from this process (renderer) to the main process. The main process then replies with "pong".

+
+
+
+ + + diff --git a/docs/fiddles/communication/two-processes/asynchronous-messages/main.js b/docs/fiddles/communication/two-processes/asynchronous-messages/main.js new file mode 100644 index 000000000000..38dc956f39ee --- /dev/null +++ b/docs/fiddles/communication/two-processes/asynchronous-messages/main.js @@ -0,0 +1,29 @@ +const { app, BrowserWindow, ipcMain } = require('electron') + +let mainWindow = null + +function createWindow () { + const windowOptions = { + width: 600, + height: 400, + title: 'Asynchronous messages', + webPreferences: { + nodeIntegration: true + } + } + + mainWindow = new BrowserWindow(windowOptions) + mainWindow.loadFile('index.html') + + mainWindow.on('closed', () => { + mainWindow = null + }) +} + +app.on('ready', () => { + createWindow() +}) + +ipcMain.on('asynchronous-message', (event, arg) => { + event.sender.send('asynchronous-reply', 'pong') +}) diff --git a/docs/fiddles/communication/two-processes/asynchronous-messages/renderer.js b/docs/fiddles/communication/two-processes/asynchronous-messages/renderer.js new file mode 100644 index 000000000000..40ed596201ad --- /dev/null +++ b/docs/fiddles/communication/two-processes/asynchronous-messages/renderer.js @@ -0,0 +1,12 @@ +const { ipcRenderer } = require('electron') + +const asyncMsgBtn = document.getElementById('async-msg') + +asyncMsgBtn.addEventListener('click', () => { + ipcRenderer.send('asynchronous-message', 'ping') +}) + +ipcRenderer.on('asynchronous-reply', (event, arg) => { + const message = `Asynchronous message reply: ${arg}` + document.getElementById('async-reply').innerHTML = message +})