0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

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

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

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

main.js
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();
});
preload.js
const { contextBridge, ipcRenderer } = require('electron')
 
contextBridge.exposeInMainWorld('electronAPI', {
    seyHello: (hello) => ipcRenderer.send('say-hello', hello);
});
index.html
<html>
 	<script>
 		window.electronAPI.sayHello("hello");
 	</script>
</html> 

e82c527c1f10f9de06472bfe02ec7263.png

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

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

main.js
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()
})
preload.js
const { contextBridge, ipcRenderer } = require('electron')
 
contextBridge.exposeInMainWorld('electronAPI',{
   yourName: () => ipcRenderer.invoke('whats:yourName')
})
index.html
<html>
 	<script>
 		const yourName = await window.electronAPI.yourName()
      	console.log("I'm Mitsuha Miyamizu your name:" + yourName);
 	</script>
</html>

055949ec096e7b46dbbf8ca25adcf1ad.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?