Electron-inter-process-communication

提供:Dev Guides
移動先:案内検索

電子-プロセス間通信

Electronは、 ipcMain および ipcRenderer と呼ばれる2つのIPC(プロセス間通信)モジュールを提供します。

*ipcMain* モジュールは、メインプロセスからレンダラープロセスに非同期で通信するために使用されます。 メインプロセスで使用される場合、モジュールはレンダラープロセス(Webページ)から送信される非同期および同期メッセージを処理します。 レンダラーから送信されたメッセージは、このモジュールに送信されます。
*ipcRenderer* モジュールは、レンダラープロセスからメインプロセスに非同期で通信するために使用されます。 レンダラープロセス(Webページ)からメインプロセスに同期および非同期メッセージを送信できるように、いくつかのメソッドが用意されています。 メインプロセスから返信を受け取ることもできます。

上記のモジュールを使用して互いにメッセージを送信するメインプロセスとレンダラープロセスを作成します。

次の内容で main_process.js という新しいファイルを作成します-

const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
const {ipcMain} = require('electron')

let win

function createWindow() {
   win = new BrowserWindow({width: 800, height: 600})
   win.loadURL(url.format ({
      pathname: path.join(__dirname, 'indexl'),
      protocol: 'file:',
      slashes: true
   }))
}

//Event handler for asynchronous incoming messages
ipcMain.on('asynchronous-message', (event, arg) => {
   console.log(arg)

  //Event emitter for sending asynchronous messages
   event.sender.send('asynchronous-reply', 'async pong')
})

//Event handler for synchronous incoming messages
ipcMain.on('synchronous-message', (event, arg) => {
   console.log(arg)

  //Synchronous event emmision
   event.returnValue = 'sync pong'
})

app.on('ready', createWindow)

新しい indexl ファイルを作成し、次のコードを追加します。

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8">
      <title>Hello World!</title>
   </head>

   <body>
      <script>
         const {ipcRenderer} = require('electron')

        //Synchronous message emmiter and handler
         console.log(ipcRenderer.sendSync('synchronous-message', 'sync ping'))

        //Async message handler
         ipcRenderer.on('asynchronous-reply', (event, arg) => {
            console.log(arg)
         })

        //Async message sender
         ipcRenderer.send('asynchronous-message', 'async ping')
      </script>
   </body>
</html>

次のコマンドを使用してアプリを実行します-

$ electron ./main_process.js

上記のコマンドは、次の出力を生成します-

//On your app console
Sync Pong
Async Pong

//On your terminal where you ran the app
Sync Ping
Async Ping

レンダラープロセスで重いタスクやブロッキングタスクの計算を実行しないことをお勧めします。 これらのタスクをメインプロセスに委任するには、常にIPCを使用します。 これは、アプリケーションのペースを維持するのに役立ちます。