본문 바로가기

컴퓨터/Electron

Electron IPC

1. IPC 란? Electron 에서 렌더러 프로세스와 메인 프로세스 간에 데이터를 주고 받는 것을 Inter-Process Communication 이라고 한다. 

2. 렌더러 프로세스 → 메인 프로세스

ipcRenderer 모듈의 ipcRenderer.send 메서드로 보내고 ipcMain 모듈의 ipcMain.on 메서드로 받는다.

3. 메인 프로세스 → 렌더러 프로세스

ipcMain 모듈의 webContents.send 메서드로 보내고 ipcRenderer.on 메서드로 받는다.

4. 예제

  1) main.js

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

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  mainWindow.loadFile('index.html');

  ipcMain.on('ping', (event, arg) => {
    console.log(arg); // "hello"
    event.reply('pong', 'world');
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

  2) index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>IPC Example</title>
  </head>
  <body>
    <button id="ping-button">Ping</button>
    <script src="renderer.js"></script>
  </body>
</html>

  3) renderer.js

const { ipcRenderer } = require('electron');

const pingButton = document.getElementById('ping-button');

pingButton.addEventListener('click', () => {
  ipcRenderer.send('ping', 'hello');
});

ipcRenderer.on('pong', (event, arg) => {
  console.log(arg); // "world"
});

'컴퓨터 > Electron' 카테고리의 다른 글

Electron Reload  (0) 2023.04.26
Electron 환경변수  (0) 2023.04.26
Electron path  (0) 2023.04.24
Electron HTML 보여주기  (0) 2023.04.24
Electron 모듈화  (0) 2023.04.24