Repository navigation
refactor: remove Node.js shims from sandboxed preload scripts - #53891
Merged
MarshallOfSound merged 2 commits intoSep 17, 2026
Merged
MarshallOfSound merged 2 commits into
MarshallOfSound merged 2 commits into
Conversation
ckerr
reviewed
Sep 14, 2026
|
Release note looks good now. |
erickzhao
approved these changes
Sep 15, 2026
erickzhao
left a comment
Member
There was a problem hiding this comment.
API LGTM
Broadly, this seems like a palatable change because these shims were always a bit confusing.
deepak1556
approved these changes
Sep 17, 2026
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.
MarshallOfSound
force-pushed
the
refactor/sandbox-preload-drop-node-shims
branch
from
September 17, 2026 19:12
207e187 to
9d9efea
Compare
codebytere
approved these changes
Sep 17, 2026
|
Release Notes Persisted
|
MarshallOfSound
deleted the
refactor/sandbox-preload-drop-node-shims
branch
September 17, 2026 22:07
Contributor
|
I was unable to backport this PR to "45-x-y" cleanly; |
MarshallOfSound
added a commit
that referenced
this pull request
Sep 18, 2026
* 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)
MarshallOfSound
added a commit
that referenced
this pull request
Sep 18, 2026
* 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)
MarshallOfSound
added a commit
that referenced
this pull request
Sep 20, 2026
…tartup (45-x-y) (#54048) * perf: make the sandboxed preload Buffer global lazy (#53855) 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 (#53891) * 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) * refactor: implement EventEmitter natively for sandboxed preload bundles (#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) * refactor: run webContents.executeJavaScript and friends over mojo (#53969) * 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++ (#53970) * 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) * refactor: set up window overrides and <webview> focus/visibility natively (#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) * perf: skip renderer set-up for sandboxed documents with nothing to inject (#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: provide the renderer API modules from their bindings (#53973) * 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) * refactor: run sandboxed preload scripts without an Electron JavaScript 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)
2 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description of Change
require('events' | 'timers' | 'url')or the implicitBuffer,setImmediate,clearImmediateparameters.require('electron'),processandglobalare unchanged. These were browser polyfills that apps bundling a preload typically already duplicate with their own shims, and an app that relied on one can trivially add it back to its preload bundle.urlandbuffernpm deps, the timers shim, and perf: make the sandboxed preload Buffer global lazy #53855's lazy-Buffer/ wrapper-shape code-cache keying (the parameter list is fixed again; the parameter-list source trailer stays).Linux x64 release, per sandboxed document commit (median of 14):
sandbox_bundle.jspreload_realm_bundle.jsBREAKING CHANGE
Checklist
npm testpassesRelease Notes
Notes: Removed the
events,timersandurlmodules and theBuffer,setImmediateandclearImmediateglobals from sandboxed preload scripts; use a polyfill.