0Pricing
Electron Desktop App Development · درس

الاتصال بين العمليات (IPC)

تعلّم تطبيق قنوات اتصال آمنة بين العمليتين الرئيسية وعمية العرض باستخدام وحدات IPC في Electron مثل `ipcMain` و`ipcRenderer`

الاتصال بين العمليات (IPC) درس مجاني في Electron Desktop App Development على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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/7) وفتح باقي دورة Electron Desktop App Development، انتقل إلى CoddyKit PRO. تتضمن دورة Electron Desktop App Development 4 دروس في المجموع.

ماذا ستتعلم في «الاتصال بين العمليات (IPC)»؟

تعلّم تطبيق قنوات اتصال آمنة بين العمليتين الرئيسية وعمية العرض باستخدام وحدات IPC في Electron مثل `ipcMain` و`ipcRenderer` تتمرن على Electron Desktop App Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Electron Desktop App Development؟

لا تُشترط خبرة سابقة. Electron Desktop App Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «الاتصال بين العمليات (IPC)»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Electron Desktop App Development هذا؟

نعم. كل درس في Electron Desktop App Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. العملية الرئيسية مقابل عملية العرض
  2. الاتصال بين العمليات (IPC)
  3. حزم تطبيق Electron
  4. إدارة نوافذ متعددة
← العودة إلى Electron Desktop App Development