📄

Electron プロセス間通信学習ログ

この記事は公開から2年以上経過しています。内容が古くなっている可能性があります。

Electronにはプロセス間通信というものがあります。 そのプロセス間通信が少しややこしかったので図にして学習した記録を載せます。

プロセス間通信(片方向)

IPC:あいぴーしー:interprocess communication:動作中のプログラムの間でデータの交換をすること:プロセス間通信

ipcRenderer.sendipcMain.onを使用して実現する

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
 
function createWindow () {
   const mainWindow = new BrowserWindow({
     webPreferences: {
       preload: path.join(__dirname, 'preload.js');
     }
   })
   mainWindow.loadFile('index.html');
}
 
app.whenReady().then(() => {
   ipcMain.on('say-hello', (event, hello) => console.log(hello));
   createWindow();
});
const { contextBridge, ipcRenderer } = require('electron')
 
contextBridge.exposeInMainWorld('electronAPI', {
    seyHello: (hello) => ipcRenderer.send('say-hello', hello);
});
<html>
 	<script>
 		window.electronAPI.sayHello("hello");
 	</script>
</html> 

e82c527c1f10f9de06472bfe02ec7263.png

プロセス間通信(双方向)

ipcRenderer.invokeipcMain.handleを対にして使うことで実現

const {app, BrowserWindow, ipcMain, dialog} = require('electron')
const path = require('path')
 
async function handleYourName() {
   return "Taki Tachibana"
}
 
function createWindow () {
   const mainWindow = new BrowserWindow({
     webPreferences: {
       preload: path.join(__dirname, 'preload.js')
     }
   })
   mainWindow.loadFile('index.html')
}
 
app.whenReady().then(() => {
   ipcMain.handle('whats:yourname', handleYourName)
   createWindow()
})
const { contextBridge, ipcRenderer } = require('electron')
 
contextBridge.exposeInMainWorld('electronAPI',{
   yourName: () => ipcRenderer.invoke('whats:yourName')
})
<html>
 	<script>
 		const yourName = await window.electronAPI.yourName()
      	console.log("I'm Mitsuha Miyamizu your name:" + yourName);
 	</script>
</html>

055949ec096e7b46dbbf8ca25adcf1ad.png

新着記事

関連ネットワーク(beta)

ドラッグで移動 / Ctrl+ホイールでズーム