Skip to content

perf: remove Electron's injected JavaScript from sandboxed renderer startup (45-x-y) - #54048

Merged
MarshallOfSound merged 9 commits into
45-x-yfrom
bp/45-x-y/sandboxed-renderer-zero-js
Sep 20, 2026
Merged

MarshallOfSound merged 9 commits into
45-x-yfrom
bp/45-x-y/sandboxed-renderer-zero-js

Conversation

@MarshallOfSound

Copy link
Copy Markdown
Member

Backport of #53855, #53891, #53892, #53969, #53970, #53971, #53972, #53973 and #53974

See those PRs for details. One commit per original PR, cherry-picked in order; conflicts were limited to package.json/yarn.lock (dependency removals), typings/internal-electron.d.ts and the preload-sandbox.js fixture.

Notes:

  • Reduced sandboxed renderer startup work for preload scripts that do not use Buffer.
  • Removed the events, timers and url modules and the Buffer, setImmediate and clearImmediate globals from sandboxed preload scripts; use a polyfill.
  • Made sandboxed renderers without a preload script start faster.
  • Made sandboxed preload scripts start faster; Electron no longer evaluates a JavaScript bundle of its own in sandboxed renderers unless webviewTag is enabled.

@MarshallOfSound
MarshallOfSound requested review from a team as code owners September 17, 2026 22:39
@MarshallOfSound MarshallOfSound added backport This is a backport PR semver/major incompatible API changes 45-x-y labels Sep 17, 2026
@trop trop Bot mentioned this pull request Sep 17, 2026
6 tasks done
@trop trop Bot added backport/requested 🗳 semver/patch backwards-compatible bug fixes labels Sep 17, 2026

@ckerr ckerr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am really uncomfortable with the idea of omnibus backports like this one. I do see the appeal here: these PRs were a thematically related stack, and it's better than the alternative of One Big PR in main.

But even so, +4701 -1873 is a lot. Please use this idiom with restraint.

For the code itself, I reviewed most of these PRs when PRed to main and they LGTM.

@MarshallOfSound

MarshallOfSound commented Sep 17, 2026 •

Copy link
Copy Markdown
Member Author

@ckerr Hm, I just changed trop to do this automatically for PR stacks (which I think we would be more comfortable with). To be clear every single one of these was a clean cherry pick (and byte for byte identical to main, excluding tests and yarn.lock).

The goal was to reduce CI churn and time-to-merge (9 PRs would be by definition 9x more expensive). I think the idea of a big stack on main and single backport PRs from trop (to prove it's clean) is the ideal case for review-ability + CI cost. What do you think?

@MarshallOfSound
MarshallOfSound enabled auto-merge (squash) September 17, 2026 23:26
@MarshallOfSound MarshallOfSound removed the semver/patch backwards-compatible bug fixes label Sep 18, 2026
@MarshallOfSound
MarshallOfSound force-pushed the bp/45-x-y/sandboxed-renderer-zero-js branch from 94b43c7 to 13c8bbb Compare September 18, 2026 06:20

@ckerr ckerr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MarshallOfSound I think on balance I like the idea of omnibus backports when used in the way this PR does them: they're all of a consistent theme, parts of a main PR stack that make sense as a group. Backporting this way saves submitter time, reviewer time, CI time.

It hasn't happened yet, but my concern was more opening the door to grouping unrelated or tangentally-related PRs into an omnibus backport. Let's avoid that.

@MarshallOfSound

Copy link
Copy Markdown
Member Author

It hasn't happened yet, but my concern was more opening the door to grouping unrelated or tangentally-related PRs into an omnibus backport. Let's avoid that.

Big agree 👍

MarshallOfSound and others added 9 commits September 18, 2026 22:53
With context isolation the preload realm's global is private to preloads, so
Buffer is defined there as a property that loads the polyfill on first use
instead of evaluating it for every frame before any preload runs. Without
context isolation it stays a preload-scoped parameter as before.

The persisted preload code cache is now also keyed on that wrapper shape,
because V8's cached-data check does not notice a changed parameter list.

Also drops the `Buffer` hidden value set on the sandboxed global; its native
consumer was removed in #34794.

With the wrapper shape now depending on where the bundle runs, the renderer
decides it from the actual script context (main world vs isolated world)
rather than the contextIsolation preference, and names the parameter list in
the compiled source so a persisted code cache produced for one shape is
rejected rather than run against the other.

(cherry picked from commit 0ef9950)
* refactor: remove Node.js shims from sandboxed preload scripts

BREAKING CHANGE. Sandboxed preload scripts and service worker preload
scripts no longer get the `events`, `timers` and `url` module shims from
`require`, and are no longer run with `Buffer`, `setImmediate` and
`clearImmediate` in scope. `require` only loads `electron`; `process` and
`global` are still provided.

These were npm browser polyfills compiled into the bundle that every
sandboxed renderer evaluates, and made up about two thirds of it. With them
gone the preload wrapper's parameter list is fixed again, so the code cache
no longer needs to be keyed on the wrapper shape.

* docs: tabulate the removed preload shims and their replacements

(cherry picked from commit 05f60b5)
…es (#53892)

* refactor: implement EventEmitter natively for sandboxed preload bundles

Adds a C++ implementation of the `EventEmitter` class
(shell/common/gin_helper/node_event_emitter.cc, exposed through the
`electron_common_events` binding) and resolves `events` to it in the
bundles that run without a Node.js environment, so `ipcRenderer`,
`webFrame` and the sandboxed preload `process` object no longer pull the
`events` npm package into every sandboxed renderer.

The class provides the same instance API the `events` package did and
nothing more: on/once/off/emit/addListener/removeListener/prependListener/
prependOnceListener/removeAllListeners/listeners/rawListeners/
listenerCount/eventNames/setMaxListeners/getMaxListeners, the
'newListener' and 'removeListener' events, the max-listener console
warning and `EventEmitter.defaultMaxListeners`. As in lib/events.js the
listener state lives in `_events` / `_eventsCount` / `_maxListeners` on
the instance, so the methods are generic over their receiver and classes
can extend it. A spec runs the same scenarios against Node's EventEmitter
and this one and requires identical results.

* perf: dispatch IPC messages to listeners without going through JS

The native EventEmitter keeps `_events`, `_eventsCount` and
`_maxListeners` in internal fields on real instances (still surfaced as
the usual own data properties), caches its property keys, builds once()
wrappers by binding one shared native function instead of minting a new
function per call, and calls straight into its own C++ bodies for the
internal `this.emit()` / `this.on()` / `this.removeListener()` calls when
those methods are not overridden.

It also exports EmitEvent(), and ipc_native::EmitIPCEvent() now builds the
event object and emits on ipcRenderer / ipcRendererInternal from C++
instead of calling a JS `onMessage` trampoline that called `emit()`. In a
renderer with Node.js integration the emitters are Node's and EmitEvent()
calls their `emit` method.

* perf: call multiple listeners for one event from a JS loop

Calling N listeners through N v8::Function::Call() entries from C++ costs
about four times per listener what a JIT-compiled loop does. When an
event has more than one listener, hand the listener array to a one-line
`for (...) Reflect.apply(listener, self, args)` function compiled once per
context instead. The single-listener case is still one direct call from
C++. Also pins the listener-throws semantics (later listeners skipped,
emit rethrows) against Node's in the spec.

* fix: handle object event names and large removeAllListeners in the native EventEmitter

Deleting an event whose name is an arbitrary object asked v8::Object::Delete
to convert it to a property key, which needs to run script and is not
allowed there; convert it first. Emitting 'removeListener' for every
listener of an event kept all the temporary handles of the loop alive until
it finished; give each iteration its own HandleScope.

* fix: address review comments on the native EventEmitter

- removeListener() searches the listener array in place from the back
  instead of copying it first, so removing the newest listener (what once()
  wrappers and removeAllListeners() do) no longer costs a full copy each time.
- The 'removeListener' event reports the originally registered function when
  a once() wrapper is removed from a multi-listener event, as events@3 did.
- A once() wrapper is only marked fired after its removeListener() call
  succeeded, matching events@3's order.

(cherry picked from commit 5ef3e5d)
…3969)

* refactor: run webContents.executeJavaScript and friends over mojo

`webContents.executeJavaScript`, `executeJavaScriptInIsolatedWorld`,
`insertCSS`, `removeInsertedCSS`, `insertText` and
`setVisualZoomLevelLimits` used to send an internal IPC message that a
handler in the renderer's Electron bundle answered by calling `webFrame`.
They are now methods on mojom::ElectronRenderer implemented by
ElectronApiServiceImpl, so they no longer depend on Electron's JavaScript
running in the renderer. Script results still come back through Electron's
V8 serializer and a returned promise is still awaited.

* fix: address review comments on executeJavaScript over mojo

- Let Blink await a returned promise: extend the RequestExecuteScript patch
  so the raw-value callback also receives the rejection reason of an
  awaited result, use PromiseResultOption::kAwait, and reply from a plain
  function instead of the self-owned helper that chained on the promise.
- Bind the browser-side replies with base::SplitOnceCallback instead of a
  shared_ptr'd promise, and enter the promise's context before
  deserializing the result (WebFrameMain::BindPromiseToReply).

(cherry picked from commit cf50144)
* refactor: emit the renderer security warnings from C++

The "Electron Security Warning" console messages were produced by a module
in the renderer bundle that fetched the web preferences over an internal
IPC on every page load. A small RenderFrameObserver now performs the same
checks natively after the main frame loads (web preferences, command line,
CSP eval check, `[allowpopups]` elements and insecure resource timing
entries) and logs through the frame's console, so neither the sandboxed
nor the Node.js renderer bundle carries the module any more.

* test: ignore security warnings when waiting for a <webview> guest's first console message

The warnings are now logged as soon as the guest finishes loading, which can
be before a fixture logs the message a test is waiting for.

(cherry picked from commit d34c7da)
…vely (#53971)

* refactor: set up window overrides and <webview> focus/visibility natively

The renderer bundle patched `window.prompt` (to throw), `window.close` in
Node.js renderers (to close the BrowserWindow over an internal IPC), and in
<webview> guests replaced `document.visibilityState` with a copy of the
embedder window's state and reported window focus/blur to the browser so
the <webview> element could emit focus events.

- `prompt` and `close` are now installed from C++ when the context is
  created; `close` calls a new ElectronWebContentsUtility.CloseWindow().
- Guest visibility needs no shim: content propagates the embedder's
  visibility to inner WebContents, so the BrowserWindow-side forwarding and
  the renderer override are removed. The previously disabled <webview>
  visibility spec is rewritten to cover hide/show.
- Guest focus/blur is reported by a native DOM event listener through
  ElectronWebContentsUtility.NotifyGuestFocusChange(), which emits the same
  `-focus-change` event the guest view manager already forwards.

* fix: skip guest focus reports from a window already detached from its frame

(cherry picked from commit 9ced348)
…ject (#53972)

Every document in a frame Electron manages had a main-world script context
forced into existence at DidClearWindowObject, the sandbox bundle run in it
and, with context isolation, an isolated world created, even when the
renderer is sandboxed and there are no preload scripts and no <webview>
support to set up. In that case nothing can observe the result, so all
three steps are now skipped, and the context is no longer forced for
frames Electron never injects into (subframes without
nodeIntegrationInSubFrames). A message sent to such a document is dropped
quietly instead of logging an error.

(cherry picked from commit 7c0b7cc)
* refactor: create ipcRenderer natively

`ipcRenderer` and the internal `ipcRendererInternal` were JavaScript
classes extending EventEmitter that forwarded to an `electron_renderer_ipc`
binding object, and a start-up module registered them as the targets for
incoming messages. The binding now builds both objects itself when it is
loaded into a context: instances of the shared native EventEmitter class
with `send`/`sendSync`/`invoke`/`postMessage`/`sendToHost` implemented in
C++ on an intermediate prototype (so, as before, they are not own
properties and work unbound), and it registers them for incoming messages.
The TypeScript modules re-export the binding's objects.

gin_helper::GetNodeEventEmitterConstructor() caches one EventEmitter class
per context so that these objects and the class exposed to scripts share a
prototype.

* refactor: create contextBridge natively

The `contextBridge` module was a JavaScript wrapper that checked
`process.contextIsolated` and forwarded to the
`electron_renderer_context_bridge` binding. The binding now exports the
module object directly, doing the context isolation check in C++ (the
frame's web preference, or always allowed in a service worker preload
realm), and in debug builds attaches the `internalContextBridge` helpers
the tests use.

* refactor: make webFrame an EventEmitter natively

The `webFrame` module wrapped the `electron_renderer_web_frame` binding in
JavaScript to make `WebFrame` an EventEmitter, to start emitting
'isolated-world-created' when something first listens for it, and to
implement the deprecated `routingId` / `findFrameByRoutingId()` with a
synchronous internal IPC to the browser.

The binding now chains `WebFrame.prototype` to the context's native
EventEmitter, hooks `on()` and friends for the lazy 'isolated-world-created'
registration, and implements the two deprecated members over a sync call on
ElectronWebContentsUtility, so the browser-side IPC handlers go away. The
renderer `crashReporter` module likewise re-exports its binding.

* refactor: receive transferred shared textures in the renderer natively

`sharedTexture.sendSharedTexture()` reached the target frame through an
internal IPC round trip answered by the renderer-side `sharedTexture`
module, which imported the texture, replied with its sync token and called
the receiver registered with `setSharedTextureReceiver()`.

That now happens over mojom::ElectronFrame::ReceiveSharedTexture(),
implemented by ElectronApiServiceImpl: it imports the texture with the
`electron_common_shared_texture` binding in the frame's Electron context,
replies with the frame creation sync token (or the error), and invokes the
registered receiver with the same `{ importedSharedTexture }` object as
before. The receiver is registered natively by the binding, so the
renderer module is a plain re-export and the last `invokeInWebFrameMain`
helper is removed.

* fix: address review comments on the native renderer API modules

- Import a transferred shared texture by calling
  shared_texture::FinishTransferSharedTexture() directly rather than going
  through the binding's exports object.
- WebFrame's listener hooks carry the EventEmitter.prototype method they
  defer to as callback data instead of looking it up on every call.

(cherry picked from commit fb221b6)
…t bundle (#53974)

Sandboxed renderers and service worker preload realms ran a webpack bundle
(sandbox_bundle / preload_realm_bundle) that built the preload scripts'
`process` object and `require`, assembled the `electron` module from the
JavaScript API wrappers, registered the <webview> element and then compiled
and ran each preload script. With the API modules now provided by their
bindings, the rest moves to C++ (shell/renderer/preload_environment.cc):

- `process` is a native EventEmitter carrying the same properties as
  before, plus getProcessMemoryInfo(); 'loaded', 'exit', 'document-start'
  and 'document-end' are emitted on it directly.
- `require('electron')` returns a module object whose properties load their
  binding on first access.
- Preload scripts are compiled with CreatePreloadScript() and called with
  (require, process, exports, module, global); failures are logged and
  reported as 'preload-error' as before.

The only JavaScript Electron still evaluates in a sandboxed renderer is the
<webview> element implementation, now its own `webview_bundle`, and only in
renderers that enable `webviewTag`. The `process` npm polyfill is no longer
needed.

(cherry picked from commit 7d3cf33)
@MarshallOfSound
MarshallOfSound merged commit 197080b into 45-x-y Sep 20, 2026
132 of 134 checks passed
@MarshallOfSound
MarshallOfSound deleted the bp/45-x-y/sandboxed-renderer-zero-js branch September 20, 2026 00:06
@release-clerk

release-clerk Bot commented Sep 20, 2026

Copy link
Copy Markdown

Release Notes Persisted

  • Reduced sandboxed renderer startup work for preload scripts that do not use Buffer.
  • Removed the events, timers and url modules and the Buffer, setImmediate and clearImmediate globals from sandboxed preload scripts; use a polyfill.
  • Made sandboxed renderers without a preload script start faster.
  • Made sandboxed preload scripts start faster; Electron no longer evaluates a JavaScript bundle of its own in sandboxed renderers unless webviewTag is enabled.

boris-w added a commit to boris-w/cupper that referenced this pull request Nov 13, 2026
…n 45

Electron 45.2.3 carries electron/electron#54048, the backport of #53971:
its own show/hide listener, which threw "Object has been destroyed" on a
destroyed window, is gone from the framework. The closed window's
cleanup T260 added for 44 has nothing left to guard against.

Refs: T107
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

45-x-y backport/approved ✅ backport This is a backport PR semver/major incompatible API changes

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants