Browse Source

docs: add Synchronous Messages Fiddle example (#20451)

* docs: add Synchronous Messages Fiddle example

* Code review changes

* Add OS support info
Amarnath Karthi 5 years ago
parent
commit
0fe718b1d9

+ 27 - 0
docs/fiddles/communication/two-processes/synchronous-messages/index.html

@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8">
+  </head>
+  <body>
+    <div>
+      <div>
+        <h1>Synchronous messages</h1>
+        <i>Supports: Win, macOS, Linux <span>|</span> Process: Both</i>
+        <div>
+          <div>
+            <button id="sync-msg">Ping</button>
+            <span id="sync-reply"></span>
+          </div>
+          <p>You can use the <code>ipc</code> module to send synchronous messages between processes as well, but note that the synchronous nature of this method means that it <b>will block</b> other operations while completing its task.</p>
+          
+          <p>This example sends a synchronous message, "ping", from this process (renderer) to the main process. The main process then replies with "pong".</p>
+        </div>
+      </div>
+    </div>
+    <script>
+      // You can also require other files to run in this process
+      require('./renderer.js')
+    </script>
+  </body>
+</html> 

+ 29 - 0
docs/fiddles/communication/two-processes/synchronous-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: 'Synchronous Messages',
+    webPreferences: {
+      nodeIntegration: true
+    }
+  }
+
+  mainWindow = new BrowserWindow(windowOptions)
+  mainWindow.loadFile('index.html')
+
+  mainWindow.on('closed', () => {
+    mainWindow = null
+  })
+}
+
+app.on('ready', () => {
+  createWindow()
+})
+
+ipcMain.on('synchronous-message', (event, arg) => {
+    event.returnValue = 'pong'
+})

+ 9 - 0
docs/fiddles/communication/two-processes/synchronous-messages/renderer.js

@@ -0,0 +1,9 @@
+const { ipcRenderer } = require('electron')
+
+const syncMsgBtn = document.getElementById('sync-msg')
+
+syncMsgBtn.addEventListener('click', () => {
+    const reply = ipcRenderer.sendSync('synchronous-message', 'ping')
+    const message = `Synchronous message reply: ${reply}`
+    document.getElementById('sync-reply').innerHTML = message
+})