0Pricing
Electron Desktop App Development · レッスン

プロセス間通信(IPC)

`ipcMain`や`ipcRenderer`などのElectronのIPCモジュールを使い、mainプロセスとrendererプロセス間に安全な通信チャネルを実装する方法を学びます。

「プロセス間通信(IPC)」はCoddyKit上の無料Electron Desktop App Developmentレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはElectron Desktop App Development学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Electron Desktop App Developmentコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

What is IPC in Electron?

In Electron, your application runs across two main types of processes: the Main Process and Renderer Processes.

  • The Main Process manages the app's lifecycle and interacts with the operating system.
  • Renderer Processes (web pages) display your UI and run your web code.

They can't directly access each other's resources or global variables. This is where Inter-Process Communication (IPC) comes in!

Why IPC is Essential

Imagine your Renderer Process needs to:

  • Read a file from the user's computer.
  • Open a native dialog box.
  • Perform a heavy task without freezing the UI.

These actions require access to Node.js modules or the OS, which are restricted to the Main Process for security and stability. IPC provides a safe way for these processes to talk to each other.

IPC Core Modules: ipcMain & ipcRenderer

Electron provides two special modules for IPC:

  • ipcMain: Used in the Main Process to listen for and send messages.
  • ipcRenderer: Used in Renderer Processes to send messages to the main process and listen for replies.

These modules are the backbone of communication between your Electron app's different parts.

Renderer to Main: One-Way Send

The most common communication is from a Renderer Process to the Main Process. You can send a message using ipcRenderer.send().

This is useful for triggering native actions or requesting data from the main process without needing an immediate reply in the renderer.

Code: Renderer to Main (Client)

Here's how your renderer.js would send a message when a button is clicked. You'd also need an index.html with a button (<button id="myButton">) that loads this script.

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

document.addEventListener('DOMContentLoaded', () => {
  const btn = document.getElementById('myButton');
  if (btn) {
    btn.addEventListener('click', () => {
      ipcRenderer.send('channel-name', 'Hello from Renderer!');
      console.log('Renderer sent message.');
    });
  }
});

Code: Renderer to Main (Server)

This is the main.js code. It sets up the Electron window and uses ipcMain.on() to listen for messages on the specified 'channel-name'.

Note: nodeIntegration and contextIsolation are simplified here. For secure apps, use preload scripts.

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

let mainWindow;

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

  mainWindow.loadFile('index.html');
  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

app.whenReady().then(() => {
  createWindow();

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

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

// Handle messages from the renderer process
ipcMain.on('channel-name', (event, message) => {
  console.log('Main process received:', message);
  // Acknowledge or perform an action
});

Main to Renderer: One-Way Send

The Main Process can also send messages to a Renderer Process using mainWindow.webContents.send().

This is useful for pushing updates from the main process (e.g., progress updates, data changes) to the UI without the renderer having to request them.

Code: Main to Renderer (Server)

This main.js will send a message to the renderer once the window has finished loading. This time, the ipcMain isn't listening, but sending!

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

let mainWindow;

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

  mainWindow.loadFile('index.html');

  // Send a message to the renderer after the window is ready
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send('main-channel', 'Update from Main!');
    console.log('Main sent message to renderer.');
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.whenReady().then(() => {
  createWindow();

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

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

Code: Main to Renderer (Client)

In your renderer.js, you'll use ipcRenderer.on() to listen for messages coming from the main process. We'll display it in a <div id="messageDisplay">.

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

document.addEventListener('DOMContentLoaded', () => {
  const messageDiv = document.getElementById('messageDisplay');
  if (messageDiv) {
    ipcRenderer.on('main-channel', (event, message) => {
      messageDiv.innerText = `Received: ${message}`;
      console.log('Renderer received:', message);
    });
  }
});

Request/Reply with Invoke & Handle

For more complex interactions where the Renderer needs a response from the Main Process, Electron offers a request/reply pattern.

  • ipcRenderer.invoke(channel, ...args): Sends a message from renderer and waits for a response.
  • ipcMain.handle(channel, listener): In the main process, sets up a handler function that processes the request and returns a value (or a Promise that resolves to a value).

This allows for more structured and asynchronous communication.

Quick Check: IPC Methods

Which of the following statements about Electron's IPC modules are TRUE?

Recap: Inter-Process Communication

Great job! You've learned the fundamentals of Electron's Inter-Process Communication.

  • IPC is vital for Main and Renderer Processes to safely interact.
  • ipcMain and ipcRenderer are the core modules.
  • One-way communication uses ipcRenderer.send() (Renderer to Main) and webContents.send() (Main to Renderer).
  • For request/reply patterns, ipcRenderer.invoke() and ipcMain.handle() provide a robust solution.

You're now ready to build more interactive and powerful Electron applications!

よくある質問

「プロセス間通信(IPC)」レッスンは無料ですか?

はい。「プロセス間通信(IPC)」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Electron Desktop App Developmentコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Electron Desktop App Developmentコースには全4レッスンが含まれています。

「プロセス間通信(IPC)」で何を学びますか?

`ipcMain`や`ipcRenderer`などのElectronのIPCモジュールを使い、mainプロセスとrendererプロセス間に安全な通信チャネルを実装する方法を学びます。 ブラウザで直接実行するハンズオンコードでElectron Desktop App Developmentを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Electron Desktop App Developmentを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのElectron Desktop App Developmentは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「プロセス間通信(IPC)」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このElectron Desktop App Developmentレッスンでコードを書いて実行できますか?

はい。すべてのElectron Desktop App Developmentレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. mainプロセスとrendererプロセス
  2. プロセス間通信(IPC)
  3. Electronアプリのパッケージ化
  4. 複数ウィンドウの管理
← Electron Desktop App Developmentに戻る