Skip to content

Electron Quick Start

This document applies to the full managed mode (managed), where the application itself is Electron and the Adapter manages the Native SDK. If you only need standalone Browser reporting or already have a native host, read Access Method Selection first.

Preparation and Installation

Prepare the native RUM application ID for the target platform, along with an available DataKit address, or a DataWay address and Client Token. These are configured in the Main Process; the Native SDK manages Session, sampling, users, global context, persistence, and uploads. The Renderer placeholder configuration is not used to create a standalone web application and does not take on upload responsibilities.

Installation requires Node.js 18+. On Windows, you also need the Microsoft Visual C++ v14 Redistributable and Windows Universal CRT that match the target architecture. See Support Scope for Electron and platform requirements.

Electron Native Adapter Version

Install in an existing Electron project:

npm install @cloudcare/electron-native-adapter@alpha @cloudcare/browser-rum

postinstall downloads and verifies the matching Native Runtime for the current platform; no local compilation is required. Keep the installation script; this example does not set native.directory. For offline, custom runtime, and native host integration, see the platform-specific topics; you do not need to install vcpkg for first-time integration.

Main: Initialize and Register Windows

Merge the following code into your application's CommonJS main process entry, for example main.cjs. Wait for Electron to be ready and for bootstrap() to complete before creating and loading windows.

const electron = require("electron");
const { app, BrowserWindow } = electron;
const { bootstrap } = require("@cloudcare/electron-native-adapter");

let client;
let stopping = false;
let stopped = false;

// Electron does not automatically wait for asynchronous exit callbacks.
app.on("before-quit", (event) => {
  if (!client || stopped) return;
  event.preventDefault();
  if (stopping) return;
  stopping = true;
  client.stop().catch(console.error).finally(() => {
    stopped = true;
    app.quit();
  });
});

app.whenReady().then(async () => {
  client = await bootstrap({
    electron,
    native: {
      mode: "managed",
      settings: {
        applicationId: "<RUM 应用 ID>",
        datakitUrl: "http://127.0.0.1:9529",
        service: "electron-desktop",
        environment: "prod",
        version: app.getVersion(),
      },
    },
    autoAttach: true,
    onError: console.error,
  });

  const window = new BrowserWindow({
    webPreferences: {
      preload: require.resolve(
        "@cloudcare/electron-native-adapter/preload/standalone",
      ),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true,
    },
  });
  await window.loadFile("index.html");
}).catch((error) => {
  console.error(error);
  app.quit();
});

app.on("window-all-closed", () => app.quit());

In this example, all windows are trusted, so autoAttach: true is used. If you only want to monitor some windows, use Manual Window Registration. Replace index.html with the page path actually generated by your application build.

When using DataWay, replace datakitUrl with datawayUrl and clientToken. Configure real credentials only in Main. The app version actually reported on macOS is determined by the application packaging information.

Preload: Set Up the Page Bridge

The preload/standalone above has already installed window.FTWebViewJavascriptBridge, so no extra Preload file is needed. It must be executed before Browser RUM initialization. If your application already has a business Preload, follow Merge Preload to integrate the installation function and bundle it into a single file.

Renderer: Initialize Page Collection

Place the following code in the Renderer entry handled by your existing frontend build tool, and make sure index.html loads the build output of that entry. Do not load source files containing npm bare module imports directly as sandboxed page scripts.

import { datafluxRum } from "@cloudcare/browser-rum";

if (typeof window.FTWebViewJavascriptBridge?.sendEvent !== "function") {
  throw new Error("Electron Native Bridge 尚未就绪");
}

datafluxRum.init({
  applicationId: "native-bridge",
  datakitOrigin: "http://127.0.0.1",
  service: "electron-renderer",
  env: "prod",
  sessionSampleRate: 100,
  trackUserInteractions: true,
});

Keep applicationId and datakitOrigin as placeholder values. When the Bridge is active, the Browser SDK hands events to Native and does not send RUM requests to this address. If the Bridge is not ready, fix the Preload and window registration first. Do not remove the check and continue initialization, and do not mix in the real application ID, Token, or session persistence configuration from Browser Standalone Reporting.

Each page to be collected runs initialization once; after a page refresh, the page entry re-initializes. Actual sampling is controlled by Native. Keep Browser at 100% to avoid reducing the sample rate a second time.

Shutdown Cleanup

The Main example already waits for client.stop() in before-quit and continues exiting after cleanup. On Windows, close the Bridge EXE started by the Adapter; on macOS, close the Native SDK initialized by the Adapter. Do not terminate the process directly instead of exiting normally. stop() completing does not mean the offline queue has been fully delivered to the server.

Verify Data Reporting

  1. Development run: Use the project's existing startup command to run the application. Confirm that Main has no initialization errors, the Bridge exists in the Renderer, and there are no Browser RUM direct upload requests in Network.
  2. Page events: Visit a page, click a button, send a request, and trigger a test error. In Guance, confirm that View, Action, Resource, and Error use the application ID configured in Native; for Long Task, trigger tasks exceeding the collection threshold.
  3. Multiple windows: Create a second window, load the same Preload, and initialize Browser RUM on that page. Confirm that both windows have data. Check session correlation while Native has not switched Session; when using manual registration, verify that unregistered windows do not generate Bridge data.
  4. Exit: Close the application normally, confirm that client.stop() completes without cleanup errors; on Windows, verify that the Bridge EXE started by this application has exited.
  5. Packaged run: Deliver the complete runtime outside the ASAR following Windows Packaging or macOS Packaging and Signing, then run the packaged artifact and repeat the checks above. Ensure the verification does not depend on absolute paths on the development machine.

After integration is complete, adjust sampling, windows, and optional collection capabilities according to Common Configuration.

Feedback

Is this page helpful?