Search code examples
typescriptelectronrpcelectron-forge

Use isolated world API in electron renderer


I have created my Electron App with

create-electron-app $projDir --template=vite-typescript

In my BrowserWindow's webpreferences I have set

contextIsolation: true
nodeIntegration: false

I have defined the API which i want to use in my Renderer context inside preload.ts like this:

const WORLD_ID: number = 1004;
const API_KEY: string = "api";

interface IApi {
    myFun: <T>(...args: any) => Promise<T>;
}

const api: IApi = {
    myFun: <T>(...args: any) => ipcRenderer.invoke("my-event", ...args) as Promise<T>
}

contextBridge.exposeInIsolatedWorld(
    WORLD_ID, API_KEY, api 
);

export { type IApi, API_KEY, WORLD_ID };

i have defined a interface.d.ts for the api:

import { type IApi, API_KEY } from '@/preload';

declare global {
    interface Window {
        [API_KEY]: IApi 
    }
}

The documentation (https://www.electronjs.org/docs/latest/api/context-bridge) suggests I can now use the api like this:

// Renderer (In isolated world id1004)

window.api.myFun()
  1. I wasn't able to find any example on how to run the Renderer in an isolated world (as so kindly remarked in the docs). Can you help?
  2. webFrame.executeInIsolatedWorld() does not work since webFrame requires the path module, which is not available in the renderer. Is there an alternative?

Solution

  • As far as I understand, isolated worlds can be used to improve security in scenarios where you want to run unknown/untrusted scripts inside your Electron app's renderer process. Imagine some kind of plugin/extension system where end users of your application can install and run scripts authored by other users. You don't want these extension scripts interfering with each other or with your own trusted renderer scripts.

    By default, scripts executed in isolated worlds have access to the DOM API and JavaScript builtins. You can use Electron's contextBridge.exposeInIsolatedWorld to let isolated scripts access additional APIs.

    For example, the following preload script exposes two APIs:

    • The extensionAPI is available in the main world. It provides a function extension.execute that allows the app's web frontend to execute a script in the isolated world 1000.
    • The processAPI is available in the isolated world 1000. It lets extension scripts access a subset of the Node.js process API, specifically the engine and library versions.
    // preload.ts
    import { contextBridge, webFrame } from "electron";
    
    const extensionAPI = {
      execute: async (source: string): Promise<void> => {
        await webFrame.executeJavaScriptInIsolatedWorld(1000, [{ code: source }]);
      },
    };
    contextBridge.exposeInMainWorld("extension", extensionAPI);
    
    const processAPI = {
      versions: process.versions
    };
    contextBridge.exposeInIsolatedWorld(1000, "process", process);
    

    Now, your frontend code, running in the main world, can call extension.execute to run execute some script in the isolated world. For example:

    extension.execute("console.log('Hello, Electron', process.versions.electron)");
    

    This example is a bit contrived and likely violates some security best practices by running all extension scripts in the same isolated world. I hope it illustrates the usage of the isolated worlds API.