렌더러에서 주로 (단방향)
렌더러 프로세스에서 주 프로세스로 단방향 IPC 메시지를 전송하려면, ipcRenderer.send
API를 사용하여 메시지를 전송한 다음 ipcMain.on
API로 수신할 수 있습니다.
보통은 이 패턴을 사용하여 웹 콘텐츠에서 주 프로세스 API를 호출합니다. 프로그래밍 방식으로 창 제목을 변경할 수 있는 간단한 앱을 만들어 이 패턴을 시연해 보겠습니다.
이 데모에서는 주 프로세스, 렌더러 프로세스, 사전 로드 스크립트에 코드를 추가해야 합니다. 전체 코드는 피들에서 확인할 수 있으며, 각 파일을 개별적으로 설명할 것입니다.
피들에서 열기1. ipcMain.on
으로 이벤트 수신하기
주 프로세스에서 ipcMain.on
API를 사용하여 set-title
채널에 IPC 수신기를 설정합니다.
main.js (주 프로세스)javascript
const { app, BrowserWindow, ipcMain } = require('electron');const path = require('path');// ...function handleSetTitle(event, title) {const webContents = event.sender;const win = BrowserWindow.fromWebContents(webContents);win.setTitle(title);}function createWindow() {const mainWindow = new BrowserWindow({webPreferences: {preload: path.join(__dirname, 'preload.js'),},});mainWindow.loadFile('index.html');}app.whenReady().then(() => {ipcMain.on('set-title', handleSetTitle);createWindow();});// ...
main.js (주 프로세스)javascript
const { app, BrowserWindow, ipcMain } = require('electron');const path = require('path');// ...function handleSetTitle(event, title) {const webContents = event.sender;const win = BrowserWindow.fromWebContents(webContents);win.setTitle(title);}function createWindow() {const mainWindow = new BrowserWindow({webPreferences: {preload: path.join(__dirname, 'preload.js'),},});mainWindow.loadFile('index.html');}app.whenReady().then(() => {ipcMain.on('set-title', handleSetTitle);createWindow();});// ...
handleSetTitle
콜백에는 IpcMainEvent
구조와 title
문자열이라는 두 개의 매개변수가 있습니다. 이 함수는 set-title
채널을 통해 메시지가 들어올 때마다 메시지 발신자에 연결된 BrowserWindow
인스턴스를 찾아 win.setTitle
API를 사용합니다.
다음 단계를 위해 index.html
과 preload.js
진입점을 로드하고 있는지 확인하세요!
2. 사전 로드를 통해 ipcRenderer.send
노출하기
앞에서 생성한 수신기에 메시지를 보내려면 ipcRenderer.send
API를 사용할 수 있습니다. 기본적으로 렌더러 프로세스에서는 노드나 일렉트론 모듈에 접근할 수 없습니다. 앱 개발자는 contextBridge
API를 사용하여 사전 로드 스크립트에서 노출할 API를 선택해야 합니다.
사전 로드 스크립트에서 다음 코드를 추가하면, 렌더러 프로세스에 전역 window.electronAPI
변수가 노출됩니다.
preload.js (사전 로드 스크립트)javascript
const { contextBridge, ipcRenderer } = require('electron');contextBridge.exposeInMainWorld('electronAPI', {setTitle: (title) => ipcRenderer.send('set-title', title),});
preload.js (사전 로드 스크립트)javascript
const { contextBridge, ipcRenderer } = require('electron');contextBridge.exposeInMainWorld('electronAPI', {setTitle: (title) => ipcRenderer.send('set-title', title),});
이제 렌더러 프로세스에서 window.electronAPI.setTitle()
함수를 사용할 수 있습니다.
보안상의 이유로 ipcRenderer.send
API 전체를 직접 노출하지 않습니다. 일렉트론 API에 대한 렌더러의 접근을 최대한 제한하세요.
3. 렌더러 프로세스 UI 구축하기
BrowserWindow
의 로드된 HTML 파일에 텍스트 입력과 버튼으로 구성된 기본 사용자 인터페이스를 추가합니다.
index.htmlhtml
<!DOCTYPE html><html><head><meta charset="UTF-8" /><!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --><metahttp-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self'"/><title>Hello World!</title></head><body>Title: <input id="title" /><button id="btn" type="button">Set</button><script src="./renderer.js"></script></body></html>
index.htmlhtml
<!DOCTYPE html><html><head><meta charset="UTF-8" /><!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --><metahttp-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self'"/><title>Hello World!</title></head><body>Title: <input id="title" /><button id="btn" type="button">Set</button><script src="./renderer.js"></script></body></html>
가져온 renderer.js
파일에 사전 로드 스크립트에서 노출된 window.electronAPI
기능을 활용하는 몇 줄의 코드를 추가하여 해당 요소에 상호 작용을 넣겠습니다.
renderer.js (렌더러 프로세스)javascript
const setButton = document.getElementById('btn');const titleInput = document.getElementById('title');setButton.addEventListener('click', () => {const title = titleInput.value;window.electronAPI.setTitle(title);});
renderer.js (렌더러 프로세스)javascript
const setButton = document.getElementById('btn');const titleInput = document.getElementById('title');setButton.addEventListener('click', () => {const title = titleInput.value;window.electronAPI.setTitle(title);});
이제 데모가 완전히 작동해야 합니다. 입력 필드를 사용하여 BrowserWindow
의 제목이 어떻게 바뀌는지 확인해 보세요!