• Stars
    star
    351
  • Rank 116,594 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Bridge JavaScript objects from the main process to the renderer process in Electron.

@electron/remote

CircleCI build status npm version

@electron/remote is an Electron module that bridges JavaScript objects from the main process to the renderer process. This lets you access main-process-only objects as if they were available in the renderer process.

โš ๏ธ Warning! This module has many subtle pitfalls. There is almost always a better way to accomplish your task than using this module. For example, ipcRenderer.invoke can serve many common use cases.

@electron/remote is a replacement for the built-in remote module in Electron, which is deprecated and will eventually be removed.

Migrating from remote

NOTE: @electron/remote requires Electron 10 or higher.

There are three things you need to do to migrate from the built-in remote module to @electron/remote.

First, you need to install it from NPM:

$ npm install --save @electron/remote

Second, @electron/remote/main must be initialized in the main process before it can be used from the renderer:

// in the main process:
require('@electron/remote/main').initialize()

Third, require('electron').remote in the renderer process must be replaced with require('@electron/remote').

// in the renderer process:

// Before
const { BrowserWindow } = require('electron').remote

// After
const { BrowserWindow } = require('@electron/remote')

Note: Since this is requiring a module through npm rather than a built-in module, if you're using remote from a sandboxed process, you'll need to configure your bundler appropriately to package the code of @electron/remote in the preload script. Of course, using @electron/remote makes the sandbox much less effective.

Note: In electron >= 14.0.0, you must use the new enable API to enable the remote module for each desired WebContents separately: require("@electron/remote/main").enable(webContents).

In electron < 14.0.0, @electron/remote respects the enableRemoteModule WebPreferences value. You must pass { webPreferences: { enableRemoteModule: true } } to the constructor of BrowserWindows that should be granted permission to use @electron/remote.

API Reference

The remote module provides a simple way to do inter-process communication (IPC) between the renderer process (web page) and the main process.

In Electron, GUI-related modules (such as dialog, menu etc.) are only available in the main process, not in the renderer process. In order to use them from the renderer process, the ipc module is necessary to send inter-process messages to the main process. With the remote module, you can invoke methods of the main process object without explicitly sending inter-process messages, similar to Java's RMI. An example of creating a browser window from a renderer process:

const { BrowserWindow } = require('@electron/remote')
let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')

In order for this to work, you first need to initialize the main-process side of the remote module:

// in the main process:
require('@electron/remote/main').initialize()

Note: In electron >= 14.0.0 the remote module is disabled by default for any WebContents instance and is only enabled for specified WebContents after explicitly calling require("@electron/remote/main").enable(webContents).

In electron < 14.0.0 the remote module can be disabled for security reasons in the following contexts:

  • BrowserWindow - by setting the enableRemoteModule option to false.
  • <webview> - by setting the enableremotemodule attribute to false.

Remote Objects

Each object (including functions) returned by the remote module represents an object in the main process (we call it a remote object or remote function). When you invoke methods of a remote object, call a remote function, or create a new object with the remote constructor (function), you are actually sending synchronous inter-process messages.

In the example above, both BrowserWindow and win were remote objects and new BrowserWindow didn't create a BrowserWindow object in the renderer process. Instead, it created a BrowserWindow object in the main process and returned the corresponding remote object in the renderer process, namely the win object.

Note: Only enumerable properties which are present when the remote object is first referenced are accessible via remote.

Note: Arrays and Buffers are copied over IPC when accessed via the remote module. Modifying them in the renderer process does not modify them in the main process and vice versa.

Lifetime of Remote Objects

Electron makes sure that as long as the remote object in the renderer process lives (in other words, has not been garbage collected), the corresponding object in the main process will not be released. When the remote object has been garbage collected, the corresponding object in the main process will be dereferenced.

If the remote object is leaked in the renderer process (e.g. stored in a map but never freed), the corresponding object in the main process will also be leaked, so you should be very careful not to leak remote objects.

Primary value types like strings and numbers, however, are sent by copy.

Passing callbacks to the main process

Code in the main process can accept callbacks from the renderer - for instance the remote module - but you should be extremely careful when using this feature.

First, in order to avoid deadlocks, the callbacks passed to the main process are called asynchronously. You should not expect the main process to get the return value of the passed callbacks.

For instance you can't use a function from the renderer process in an Array.map called in the main process:

// main process mapNumbers.js
exports.withRendererCallback = (mapper) => {
  return [1, 2, 3].map(mapper)
}

exports.withLocalCallback = () => {
  return [1, 2, 3].map(x => x + 1)
}
// renderer process
const mapNumbers = require('@electron/remote').require('./mapNumbers')
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1)
const withLocalCb = mapNumbers.withLocalCallback()

console.log(withRendererCb, withLocalCb)
// [undefined, undefined, undefined], [2, 3, 4]

As you can see, the renderer callback's synchronous return value was not as expected, and didn't match the return value of an identical callback that lives in the main process.

Second, the callbacks passed to the main process will persist until the main process garbage-collects them.

For example, the following code seems innocent at first glance. It installs a callback for the close event on a remote object:

require('@electron/remote').getCurrentWindow().on('close', () => {
  // window was closed...
})

But remember the callback is referenced by the main process until you explicitly uninstall it. If you do not, each time you reload your window the callback will be installed again, leaking one callback for each restart.

To make things worse, since the context of previously installed callbacks has been released, exceptions will be raised in the main process when the close event is emitted.

To avoid this problem, ensure you clean up any references to renderer callbacks passed to the main process. This involves cleaning up event handlers, or ensuring the main process is explicitly told to dereference callbacks that came from a renderer process that is exiting.

Accessing built-in modules in the main process

The built-in modules in the main process are added as getters in the remote module, so you can use them directly like the electron module.

const app = require('@electron/remote').app
console.log(app)

Methods

The remote module has the following methods:

remote.require(module)

  • module String

Returns any - The object returned by require(module) in the main process. Modules specified by their relative path will resolve relative to the entrypoint of the main process.

e.g.

project/
โ”œโ”€โ”€ main
โ”‚   โ”œโ”€โ”€ foo.js
โ”‚   โ””โ”€โ”€ index.js
โ”œโ”€โ”€ package.json
โ””โ”€โ”€ renderer
    โ””โ”€โ”€ index.js
// main process: main/index.js
const { app } = require('@electron/remote')
app.whenReady().then(() => { /* ... */ })
// some relative module: main/foo.js
module.exports = 'bar'
// renderer process: renderer/index.js
const foo = require('@electron/remote').require('./foo') // bar

remote.getCurrentWindow()

Returns BrowserWindow - The window to which this web page belongs.

Note: Do not use removeAllListeners on BrowserWindow. Use of this can remove all blur listeners, disable click events on touch bar buttons, and other unintended consequences.

remote.getCurrentWebContents()

Returns WebContents - The web contents of this web page.

remote.getGlobal(name)

  • name String

Returns any - The global variable of name (e.g. global[name]) in the main process.

Properties

remote.process Readonly

A NodeJS.Process object. The process object in the main process. This is the same as remote.getGlobal('process') but is cached.

Overriding exposed objects

Without filtering, @electron/remote will provide access to any JavaScript object that any renderer requests. In order to control what can be accessed, @electron/remote provides an opportunity to the app to return a custom result for any of getGlobal, require, getCurrentWindow, getCurrentWebContents, or any of the builtin module properties.

The following events will be emitted first on the app Electron module, and then on the specific WebContents which requested the object. When emitted on the app module, the first parameter after the Event object will be the WebContents which originated the request. If any handler calls preventDefault, the request will be denied. If a returnValue parameter is set on the result, then that value will be returned to the renderer instead of the default.

Events

Event: 'remote-require'

Returns:

  • event Event
  • moduleName String

Emitted when remote.require() is called in the renderer process of webContents. Calling event.preventDefault() will prevent the module from being returned. Custom value can be returned by setting event.returnValue.

Event: 'remote-get-global'

Returns:

  • event Event
  • globalName String

Emitted when remote.getGlobal() is called in the renderer process of webContents. Calling event.preventDefault() will prevent the global from being returned. Custom value can be returned by setting event.returnValue.

Event: 'remote-get-builtin'

Returns:

  • event Event
  • moduleName String

Emitted when remote.getBuiltin() is called in the renderer process of webContents, including when a builtin module is accessed as a property (e.g. require("@electron/remote").BrowserWindow). Calling event.preventDefault() will prevent the module from being returned. Custom value can be returned by setting event.returnValue.

Event: 'remote-get-current-window'

Returns:

  • event Event

Emitted when remote.getCurrentWindow() is called in the renderer process of webContents. Calling event.preventDefault() will prevent the object from being returned. Custom value can be returned by setting event.returnValue.

Event: 'remote-get-current-web-contents'

Returns:

  • event Event

Emitted when remote.getCurrentWebContents() is called in the renderer process of webContents. Calling event.preventDefault() will prevent the object from being returned. Custom value can be returned by setting event.returnValue.

More Repositories

1

electron

:electron: Build cross-platform desktop apps with JavaScript, HTML, and CSS
C++
111,759
star
2

electron-quick-start

Clone to try a simple Electron app
JavaScript
10,851
star
3

electron-api-demos

Explore the Electron APIs
HTML
10,236
star
4

fiddle

:electron: ๐Ÿš€ The easiest way to get started with Electron
TypeScript
7,312
star
5

forge

:electron: A complete tool for building and publishing Electron applications
TypeScript
6,117
star
6

asar

Simple extensive tar-like archive format with indexing
JavaScript
2,426
star
7

apps

A collection of apps built on Electron
JavaScript
1,655
star
8

electronjs.org-old

Electron website
Handlebars
1,588
star
9

windows-installer

Build Windows Installers for Electron apps
TypeScript
1,529
star
10

rcedit

Command line tool to edit resources of exe
C++
1,502
star
11

electron-quick-start-typescript

Clone to try a simple Electron app (in TypeScript)
TypeScript
1,176
star
12

rebuild

Package to rebuild native Node.js modules against the currently installed Electron version
TypeScript
980
star
13

update-electron-app

๐ŸŒฒ A drop-in module that adds autoUpdating capabilities to Electron apps
TypeScript
682
star
14

i18n

๐ŸŒ The home of Electron's translated documentation
TypeScript
623
star
15

simple-samples

Minimal Electron applications with ideas for taking them further
JavaScript
610
star
16

update.electronjs.org

๐Ÿ“ก A free service that makes it easy for open-source Electron apps to update themselves.
JavaScript
556
star
17

osx-sign

Codesign Electron macOS apps
TypeScript
538
star
18

libchromiumcontent

Shared library build of Chromiumโ€™s Content module
Python
484
star
19

get

Download Electron release artifacts
TypeScript
325
star
20

releases

๐Ÿ“ฆ Complete and up-to-date info about every release of Electron
JavaScript
245
star
21

build-tools

The GN scripts to use for Electron dev-flows
JavaScript
244
star
22

mini-breakpad-server

Minimum breakpad crash reports collecting server
CoffeeScript
237
star
23

node

Node fork to make it suitable for embedding in Electron
231
star
24

node-rcedit

Node module to edit resources of exe
JavaScript
183
star
25

node-abi

๐Ÿข ๐Ÿš€ Get the Node.js and Electron ABI for a given target and runtime
JavaScript
154
star
26

governance

Public repository for governance issues and documents
Shell
136
star
27

sheriff

Controls and monitors organization permissions across GitHub, Slack and GSuite. Built with โค๏ธ by The Electron Team
TypeScript
131
star
28

chromedriver

Download ChromeDriver for Electron
JavaScript
128
star
29

typescript-definitions

Convert the Electron API JSON file to electron.d.ts
TypeScript
120
star
30

mksnapshot

Electron mksnapshot binaries
JavaScript
102
star
31

universal

Create Universal macOS applications from two x64 and arm64 Electron applications
TypeScript
102
star
32

notarize

Notarize your macOS Electron Apps
TypeScript
95
star
33

website

:electron: The Electron website
TypeScript
89
star
34

packager

Customize and package your Electron app with OS-specific bundles (.app, .exe, etc.) via JS or CLI
TypeScript
75
star
35

trop

automate the backporting process
TypeScript
70
star
36

node-minidump

Node module to process minidump files
JavaScript
68
star
37

pdf-viewer

Fork of Chrome pdf extension to work as webui page in Electron
JavaScript
51
star
38

clerk

Verify PRs have release notes
TypeScript
48
star
39

hubdown

Convert markdown to GitHub-style HTML using a common set of remark plugins
JavaScript
39
star
40

native-mate

Fork of Chromium's gin library that makes it easier to marshal types between C++ and JavaScript.
C++
38
star
41

download-stats

โฌ‡๏ธ Download stats for Electron. Updated daily.
JavaScript
34
star
42

fuses

TypeScript
32
star
43

crashpad

Electron fork of crashpad
C++
31
star
44

symbolicate-mac

Symbolicate macOS Electron crash reports
JavaScript
30
star
45

onboarding-guide

or, "So You Want to Be an Electron Hacker"
30
star
46

chromium-breakpad

GitHub clone of the breakpad used by Chromium
C++
29
star
47

node-chromium-pickle-js

Binary value packing and unpacking library compatible with Chromium's Pickle class
JavaScript
22
star
48

electron-docs-linter

Parse and validate Electron's API documentation
JavaScript
21
star
49

nightlies

Nightly release store
19
star
50

docs-parser

Parse Electron docs in a lossless way into a JSON file
TypeScript
19
star
51

cation

Electron's PR monitoring bot
TypeScript
18
star
52

be

Scripts to help building Electron
JavaScript
18
star
53

season-of-docs-2020

๐Ÿ“– Project repository for Electron's possible participation in Google's Season of Docs
18
star
54

debian-sysroot-image-creator

Scripts to create debian sysroot image for building electron
Shell
18
star
55

dependent-repos

Public GitHub repos that depend on Electron. spiritual successor to https://github.com/electron/repos-using-electron
JavaScript
18
star
56

asar-require

Enable "require" scripts in asar archives
CoffeeScript
18
star
57

packages

A collection of all npm packages that mention `electron` in their package.json
JavaScript
17
star
58

symbol-server

Electron symbol server
TypeScript
14
star
59

unreleased

Checks for and reports commits unreleased for a specific release branch.
JavaScript
13
star
60

windows-sign

Codesign Electron apps for Windows
TypeScript
13
star
61

archaeologist

Digging up your artifacts since 2018
TypeScript
13
star
62

algolia-indices

Algolia search index data for Electron APIs, Tutorials, Packages, and Repos
JavaScript
13
star
63

fiddle-core

Run fiddles from anywhere, on any Electron release
TypeScript
13
star
64

electron-frameworks

Frameworks used by Electron
11
star
65

search-with-your-keyboard

Add keyboard navigation to your existing client-side search interface.
JavaScript
10
star
66

electron-api-historian

Find the birthday of every Electron API
JavaScript
9
star
67

gyp

Python
9
star
68

electron-api-docs

๐Ÿ“ Electron's API documentation in a structured JSON format [ARCHIVED]
JavaScript
9
star
69

build-tools-installer

Installer for Electron's wrapper toolkit for working with Electron.js source code
JavaScript
9
star
70

build-images

Base docker image used to build Electron on CI
Shell
9
star
71

github-app-auth

Gets an auth token for a repo via a GitHub app installation
TypeScript
8
star
72

electron-docs

Fetch Electron documentation as raw markdown strings
JavaScript
8
star
73

.github

organization-wide defaults for all electron/* repos
7
star
74

bugbot

Making life easier for people who report or triage Electron issues.
TypeScript
6
star
75

node-is-valid-window

Validates if a pointer to window is valid.
C++
5
star
76

circleci-oidc-secret-exchange

Provides dynamic access to secrets in exchange for a valid OIDC token
TypeScript
5
star
77

electron-translators

Everyone who has helped translate Electron's documentation into different languages.
JavaScript
5
star
78

electron-userland-reports

Slices of data about packages, repos, and users in Electron userland. Collected from the GitHub API, npm registry, and libraries.io
JavaScript
5
star
79

rfcs

5
star
80

roller

๐ŸŽตrollin on upstream ๐ŸŽต
TypeScript
4
star
81

eslint-config

ESLint config used by Electron and Electron maintained modules
JavaScript
4
star
82

tweets

3
star
83

electron-website-updater

JavaScript
3
star
84

zoilist

Nag @electron/api-wg to do API reviews
TypeScript
3
star
85

lint-roller

JavaScript
2
star
86

github-app-auth-action

TypeScript
2
star
87

libcc-check

A little tool for checking up on libchromiumcontent builds.
JavaScript
2
star
88

slack-chromium-helper

Slack bot to unfurl Chromium development URLs
TypeScript
2
star
89

electron-issues

An experiment to better understand the issues filed on the electron/electron repo
JavaScript
2
star
90

hippo

TypeScript
2
star
91

ventifact

TypeScript
2
star
92

node-orb

Shell
1
star
93

electron-notarize

Notarize your macOS Electron Apps
TypeScript
1
star
94

docs-reviewer

TypeScript
1
star