Capacitor Community Electron Platform

repository·main·Indexed 19 days ago

https://github.com/capacitor-community/electron

Community support for running Capacitor applications on desktop platforms using Electron. This project is currently unmaintained. It provides CLI commands (add, copy, run, open, update, sync) for platform management, guidance on creating Electron-compatible Capacitor plugins, and configuration for electron-builder and deep linking. Version 5.0.1 requires Capacitor 5.4.0 or higher.

Tokens
7.9K
Snippets
24
Records
33
Agent score
63%

What's inside @capacitor-community/electron

  1. How to emit and listen to events in an Electron plugin

    main

    To support Capacitor's addListener and removeListener methods in an Electron plugin, your plugin class must extend the EventEmitter class from the events Node.js module. This allows the Electron runtime to expose event-handling capabilities to the web layer.

    Implementation

    Extend EventEmitter and use this.emit(eventName, data) to trigger events.

    Client Usage

    Access the plugin via CapacitorCustomPlatform.plugins to attach listeners.

    // Plugin Implementation
    import { EventEmitter } from 'events';
    
    export default class MyPlugin extends EventEmitter {
      constructor() {
        super();
        setInterval(() => {
          this.emit('my-event', 'You successfully listened to the 10sec event!');     
        }, 10_000);
      }
    }
    
    // Client Code
    const id = CapacitorCustomPlatform.plugins.MyPlugin.addListener('my-event', console.log);
    
    // To stop listening:
    CapacitorCustomPlatform.plugins.MyPlugin.removeListener(id);
  2. Create a Capacitor Electron Plugin

    main

    To extend a Capacitor V3 compatible plugin with Electron support, follow these steps to set up the directory structure, build configuration, and registration:

    1. Directory Structure

    Create an electron folder in the root of your plugin, containing a src sub-folder. Place your implementation in electron/src/index.ts.

    2. Configuration Files

    Create the following files inside the electron folder:

    • .gitignore: Include dist.
    • .npmignore: Include src.
    • rollup.config.js: Configures the build output to electron/dist/plugin.js in CommonJS format.
    • tsconfig.json: Configures TypeScript compilation with outDir set to build.

    3. Update Root package.json

    Modify your plugin's root package.json with these changes:

    • capacitor object: Add the electron platform.
    • files array: Include electron/ to ensure the build artifacts are published.
    • scripts: Add a build-electron script and update the main build script to include the electron build step.

    4. Register the Plugin

    In your plugin's main entry point (<root>/src/index.ts), register the Electron implementation using CapacitorCustomPlatform:

    const Dialog = registerPlugin<DialogPlugin>('Dialog', {
      web: () => import('./web').then(m => new m.DialogWeb()),
      electron: () => (window as any).CapacitorCustomPlatform.plugins.DialogElectron
    });

    5. Build and Sync

    Run npm run build to compile the plugin. Once published, use npx cap sync (or copy/update) in your Capacitor app to include the new Electron platform support.

    // Example package.json modifications
    {
      "capacitor": {
        "ios": { "src": "ios" },
        "android": { "src": "android" },
        "electron": { "src": "electron" }
      },
      "files": [
        "electron/"
      ],
      "scripts": {
        "build-electron": "tsc --project electron/tsconfig.json && rollup -c electron/rollup.config.js && rimraf ./electron/build",
        "build": "npm run clean && npm run docgen && tsc && rollup -c rollup.config.js && npm run build-electron"
      }
    }
  3. Requirements and Migration for Version 4 or Above

    main

    If you are using Version 4 or later of @capacitor-community/electron, please note the following requirements and changes:

    • Capacitor Version: You must use Capacitor version 5.4.0 or higher.
    • Plugin Architecture: Version 4 and above no longer include plugins out of the box. Instead, they follow the Capacitor pattern of using separate plugins. You can find examples in the Plugin Examples Directory.
    • Compatibility: Plugins from previous versions of @capacitor-community/electron will not function in V4 or above. However, all standard web plugins will continue to function normally.
    • Migration Advice: Because the template and internal workings have changed significantly, it is recommended to create a new project for testing before attempting to migrate existing main projects.
  4. How deep link URLs are delivered to Capacitor

    main

    Once deep linking is set up, the plugin handles the underlying Electron events (open-url, second-instance, or command-line arguments on Windows).

    When a valid URL matching your customProtocol is detected, the plugin performs the following:

    1. It extracts the URL from the arguments/event.
    2. It executes your customHandler if provided.
    3. It sends the URL to the Capacitor web view by emitting an appUrlOpen event via the main window's webContents.

    In your Capacitor web application, you should listen for the appUrlOpen event to react to the incoming deep link.

  5. Add the Electron platform to your Capacitor project

    main

    To add Electron support to your existing Capacitor project, the add command (implemented via doAdd) automates the following setup steps:

    1. Creates the electron directory: A new directory named electron is created in your project root.
    2. Extracts the template: The Electron platform template is extracted into the electron directory.
    3. Copies Capacitor configuration: Your project's capacitor.config file (searched in order: .ts, .js, or .json) is copied into the electron directory.
    4. Configures package.json: The name field in the new electron/package.json is updated to match your project's appName from your Capacitor configuration. If your root package.json contains a repository field, it is also copied to the Electron platform's package.json.
    5. Installs dependencies: Runs npm i inside the electron directory to install necessary modules.

    Note: This process will fail if the electron directory already exists.

    # While the specific CLI command name is not explicitly exported in this file, 
    # it is the implementation for the 'add' command used to initialize the platform.
    npx cap add electron
  6. Access the Capacitor configuration in an Electron plugin

    main

    Electron plugins can access the capacitor.config.ts object. This configuration object is passed as the first argument to the plugin's constructor.

    Note: The configuration object may be undefined, so always implement null checks before accessing properties.

    export default class App {
      private config?: Record<string, any>;
    
      constructor(config?: Record<string, any>) {
        this.config = config;
      }
    
      getLaunchUrl(): string | undefined {
        const url = this.config?.server?.url;
        return url ? { url } : undefined;
      }
    }
  7. Configure SplashOptions for CapacitorSplashScreen

    main

    When instantiating CapacitorSplashScreen, you can provide a SplashOptions object to customize the splash screen's appearance and location.

    KeyTypeDefaultDescription
    imageFilePathstringjoin(app.getAppPath(), 'assets', 'splash.png')The local file path to the image used for the splash screen background.
    windowWidthnumber400The width of the splash screen window in pixels.
    windowHeightnumber400The height of the splash screen window in pixels.
  8. Configure ElectronCapacitorApp options

    main

    When instantiating ElectronCapacitorApp, you can customize the application behavior via the CapacitorElectronConfig and optional menu templates:

    • capacitorFileConfig.electron.splashScreenEnabled: If true, shows a splash screen while the web app loads.
    • capacitorFileConfig.electron.splashScreenImageName: The filename of the splash image (defaults to splash.png) located in the assets folder.
    • capacitorFileConfig.electron.trayIconAndMenuEnabled: If true, enables a system tray icon.
    • capacitorFileConfig.electron.hideMainWindowOnLaunch: If true, the main window remains hidden until the splash screen is dismissed.
    • capacitorFileConfig.electron.backgroundColor: Sets the background color of the main window.
    • capacitorFileConfig.electron.customUrlScheme: Defines the custom URL scheme used for loading the web app (defaults to capacitor-electron).
    • trayMenuTemplate: An array of MenuItemConstructorOptions or MenuItem objects for the system tray context menu.
    • appMenuBarMenuTemplate: An array of MenuItemConstructorOptions or MenuItem objects for the application menu bar.
  9. Configure Electron platform options

    main

    The electron configuration object is added to your capacitor.config.ts (or .json) file under the electron key. This allows you to customize the Electron wrapper's behavior, including window appearance, tray settings, and splash screen configuration.

    import { CapacitorConfig } from '@capacitor/cli';
    
    const config: CapacitorConfig = {
      appId: 'com.example.app',
      appName: 'My App',
      webDir: 'dist',
      plugins: {
        // ... other plugins
      },
      electron: {
        appId: 'com.example.app',
        appName: 'My App',
        trayIconAndMenuEnabled: true,
        splashScreenEnabled: true,
        splashScreenImageName: 'splash.png',
        backgroundColor: '#ffffff',
        hideMainWindowOnLaunch: false,
        customUrlScheme: 'my-app-scheme'
      }
    };
    
    export default config;
  10. Configure electron-builder settings

    main

    The electron-builder.config.json file defines how your Electron application is packaged, distributed, and installed. Key configuration areas include application identity, file inclusion, publishing providers, and platform-specific installer settings (NSIS for Windows, DMG for macOS).

    Note that the values in the template (like com.yourdoamnin.yourapp) are placeholders and must be updated to match your specific application identity.

    {
      "appId": "com.yourdoamnin.yourapp",
      "directories": {
        "buildResources": "resources"
      },
      "files": [
        "assets/**/*",
        "build/**/*",
        "capacitor.config.*",
        "app/**/*"
      ],
      "publish": {
        "provider": "github"
      },
      "nsis": {
        "allowElevation": true,
        "oneClick": false,
        "allowToChangeInstallationDirectory": true
      },
      "win": {
        "target": "nsis",
        "icon": "assets/appIcon.ico"
      },
      "mac": {
        "category": "your.app.category.type",
        "target": "dmg"
      }
    }