0Pricing
Electron Desktop App Development · レッスン

コンテキスト分離とPreloadスクリプト

悪意のあるスクリプトからrendererプロセスを保護するコンテキスト分離を理解・適用し、安全にAPIを公開するためのPreloadスクリプトを使用します。

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

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

Renderer Process Risks

In Electron, your application's user interface runs in a renderer process. This process is essentially a Chromium web page, meaning it's susceptible to common web vulnerabilities like Cross-Site Scripting (XSS).

  • Malicious scripts injected into your web content could potentially gain access to powerful Node.js APIs.
  • This direct access could lead to system-level operations being performed without your knowledge or consent.
  • Protecting the renderer is crucial for app security.

What is Context Isolation?

Context Isolation is a fundamental security feature in Electron. When enabled, it ensures that the JavaScript context of your web page is completely separate from Electron's internal APIs and Node.js environment.

  • It's like having two distinct JavaScript worlds within the same renderer process.
  • One world for your web content, and another for Electron/Node.js.
  • This separation prevents your web page's scripts from directly accessing sensitive APIs.

Good news: Context Isolation is enabled by default since Electron 12!

Two JavaScript Worlds

Imagine your renderer process has two invisible layers:

  • The Web Page Context: This is where your index.html, its scripts, and any loaded libraries (like React or Vue) run. It behaves just like a regular browser tab.
  • The Electron/Node.js Context: This is where Electron's internal modules and Node.js APIs (like fs for file system access) live.

Context Isolation ensures these two worlds cannot directly interact with each other's global objects (like window or document), preventing unauthorized access.

Bridging Isolated Contexts

While isolation is great for security, sometimes your web page needs to interact with native desktop features. This is where preload scripts come in.

  • A preload script runs before your web page loads, but within the Electron/Node.js context.
  • It has access to both Node.js APIs and the web page's window object (before isolation takes full effect).
  • However, to securely expose APIs to the isolated web page, we use a special tool called contextBridge.

Loading a Preload Script

To use a preload script, you must specify its path when creating your BrowserWindow in the main process. Remember to keep contextIsolation set to true for security.

Try running this basic setup:

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

function createWindow () {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true // Crucial for security!
    }
  });

  mainWindow.loadFile('index.html');
}

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

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

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

Secure API Exposure

The contextBridge module is your best friend for securely exposing functionality from your preload script to the renderer's isolated web context.

  • It acts as a secure, one-way bridge.
  • You define what functions or data you want to expose.
  • contextBridge ensures that only these defined APIs are available and that data passed between contexts is properly sanitized.

This prevents malicious scripts in the web page from tampering with your exposed APIs or gaining direct access to Node.js.

Crafting Your Preload Script

Inside your preload.js, you'll use contextBridge.exposeInMainWorld(). This method takes two arguments: a key (how the API will be named in the renderer's window object) and an object containing the functions or values you want to expose.

preload.js:

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

contextBridge.exposeInMainWorld('myAPI', {
  // Expose a simple function
  sendNotification: (message) => {
    // In a real app, you'd use ipcRenderer.send to talk to main process
    console.log(`Preload script sending notification: ${message}`);
    // Example: new Notification('Title', { body: message });
  },
  // Expose a value
  version: process.versions.electron
});

Accessing Exposed APIs

Once your preload script has exposed an API using contextBridge, your web page's JavaScript can safely access it via the window object, under the key you specified.

index.html (or a script loaded by it):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>My Electron App</title>
  </head>
  <body>
    <h1>Welcome!</h1>
    <p>Electron Version: <span id="electron-version"></span></p>
    <button id="notify-btn">Send Notification</button>

    <script>
      // Access the exposed API
      window.addEventListener('DOMContentLoaded', () => {
        document.getElementById('electron-version').innerText = window.myAPI.version;

        document.getElementById('notify-btn').addEventListener('click', () => {
          window.myAPI.sendNotification('Hello from the renderer!');
        });
      });
    </script>
  </body>
</html>

Full Example in Action

Here's the complete main.js for our app. To run this example, create three files: main.js (below), preload.js (content from Scene 7), and index.html (content from Scene 8) in the same directory.

When you run main.js, it will load index.html. The index.html then uses the myAPI object exposed by preload.js to display the Electron version and trigger a 'notification' (logged to console in this simple example).

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

function createWindow () {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true // Keep this true!
    }
  });

  mainWindow.loadFile('index.html');
  // Open DevTools to see console logs from preload and renderer
  mainWindow.webContents.openDevTools();
}

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

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

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

Context Check

Time to test your understanding of context isolation and preload scripts!

Secure Foundations

You've learned how to secure your Electron application's renderer process!

  • Context Isolation is key to preventing direct access between untrusted web content and powerful Node.js APIs.
  • Preload scripts run in an isolated environment, allowing you to bridge this gap safely.
  • contextBridge is the secure method within preload scripts to expose carefully selected APIs to your web content.

By using these features, you build a robust and secure foundation for your Electron desktop applications. Great job!

よくある質問

「コンテキスト分離とPreloadスクリプト」レッスンは無料ですか?

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

「コンテキスト分離とPreloadスクリプト」で何を学びますか?

悪意のあるスクリプトからrendererプロセスを保護するコンテキスト分離を理解・適用し、安全にAPIを公開するためのPreloadスクリプトを使用します。 ブラウザで直接実行するハンズオンコードでElectron Desktop App Developmentを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

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

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

「コンテキスト分離とPreloadスクリプト」レッスンにはどのくらい時間がかかりますか?

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

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

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

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

  1. 安全なIPCパターン
  2. コンテキスト分離とPreloadスクリプト
  3. rendererプロセスのサンドボックス化
  4. リモートコンテンツのリスクへの対策
← Electron Desktop App Developmentに戻る