Repository navigation
refactor: run sandboxed preload scripts without an Electron JavaScript bundle - #53974
Merged
MarshallOfSound merged 1 commit intoSep 17, 2026
Conversation
MarshallOfSound
force-pushed
the
refactor/native-preload-environment
branch
from
September 16, 2026 00:14
c089c30 to
273bd1b
Compare
MarshallOfSound
force-pushed
the
refactor/native-preload-environment
branch
from
September 17, 2026 19:12
273bd1b to
85bd755
Compare
MarshallOfSound
force-pushed
the
refactor/native-preload-environment
branch
from
September 17, 2026 19:50
85bd755 to
9a84cab
Compare
codebytere
approved these changes
Sep 17, 2026
MarshallOfSound
force-pushed
the
refactor/native-preload-environment
branch
from
September 17, 2026 20:32
9a84cab to
039ad7a
Compare
…t bundle
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.
MarshallOfSound
force-pushed
the
refactor/native-preload-environment
branch
from
September 17, 2026 20:52
039ad7a to
bb29906
Compare
|
Release Notes Persisted
|
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
…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
added a commit
that referenced
this pull request
Sep 18, 2026
…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
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)
5 tasks done
MarshallOfSound
added a commit
that referenced
this pull request
Sep 21, 2026
The browser pushes renderer startup data right before it commits a navigation, so the initial empty document of a frame whose first navigation is still pending or was cancelled never has it. A script context forced onto that document (DevTools Runtime.enable, webFrameMain.executeJavaScript) ran the sandbox bundle anyway and logged "Cannot destructure property 'preloadScripts' of 'binding.startupData' as it is null". Extension background pages and offscreen documents hit this whenever a DevTools client attached early. Return before injecting anything when the frame has no startup data; the document that commits afterwards gets its own context with the data in place. main and 45-x-y already behave this way through HasScriptsToInject() (#53974). Fixes #54149.
MarshallOfSound
added a commit
that referenced
this pull request
Sep 21, 2026
The browser pushes renderer startup data right before it commits a navigation, so the initial empty document of a frame whose first navigation is still pending or was cancelled never has it. A script context forced onto that document (DevTools Runtime.enable, webFrameMain.executeJavaScript) ran the sandbox bundle anyway and logged "Cannot destructure property 'preloadScripts' of 'binding.startupData' as it is null". Extension background pages and offscreen documents hit this whenever a DevTools client attached early. Return before injecting anything when the frame has no startup data; the document that commits afterwards gets its own context with the data in place. main and 45-x-y already behave this way through HasScriptsToInject() (#53974). Fixes #54149.
MarshallOfSound
added a commit
that referenced
this pull request
Sep 21, 2026
The browser pushes renderer startup data right before it commits a navigation, so the initial empty document of a frame whose first navigation is still pending or was cancelled never has it. A script context forced onto that document (DevTools Runtime.enable, webFrameMain.executeJavaScript) ran the sandbox bundle anyway and logged "Cannot destructure property 'preloadScripts' of 'binding.startupData' as it is null". Extension background pages and offscreen documents hit this whenever a DevTools client attached early. Return before injecting anything when the frame has no startup data; the document that commits afterwards gets its own context with the data in place. main and 45-x-y already behave this way through HasScriptsToInject() (#53974). Fixes #54149. Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com> Co-authored-by: Sam Attard <[email protected]>
MarshallOfSound
added a commit
that referenced
this pull request
Sep 21, 2026
* fix: skip the sandbox bundle on documents without startup data The browser pushes renderer startup data right before it commits a navigation, so the initial empty document of a frame whose first navigation is still pending or was cancelled never has it. A script context forced onto that document (DevTools Runtime.enable, webFrameMain.executeJavaScript) ran the sandbox bundle anyway and logged "Cannot destructure property 'preloadScripts' of 'binding.startupData' as it is null". Extension background pages and offscreen documents hit this whenever a DevTools client attached early. Return before injecting anything when the frame has no startup data; the document that commits afterwards gets its own context with the data in place. main and 45-x-y already behave this way through HasScriptsToInject() (#53974). Fixes #54149. Co-authored-by: Sam Attard <[email protected]> * test: add the preload-location fixture used by the new spec The spec backported from #54155 loads spec/fixtures/module/preload-location.js, which 42-x-y did not have yet. --------- Co-authored-by: trop[bot] <37223003+trop[bot]@users.noreply.github.com> Co-authored-by: Sam Attard <[email protected]>
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
sandbox_bundle/preload_realm_bundle.shell/renderer/preload_environment.ccbuilds the preload scripts'process(a nativeEventEmitterwith the same properties and events),require, and anelectronmodule whose properties load their binding on first access, then compiles and runs each preload script; failures are logged and reported aspreload-erroras before.<webview>element, now its ownwebview_bundle, loaded only whenwebviewTagis enabled. Theprocessnpm polyfill is dropped.Linux x64 release build, median of 14 cold renderers, time inside the main-world
LocalWindowProxy::Initialize(Electron's share excludes Blink's own context set-up):webviewTagonChecklist
npm testpassesRelease Notes
Notes: Made sandboxed preload scripts start faster; Electron no longer evaluates a JavaScript bundle of its own in sandboxed renderers unless
webviewTagis enabled.