Skip to content

refactor: emit WebContents' forwarded events natively - #53975

Merged
MarshallOfSound merged 7 commits into
mainfrom
perf/native-webcontents-events
Sep 16, 2026
Merged

MarshallOfSound merged 7 commits into
mainfrom
perf/native-webcontents-events

Conversation

@MarshallOfSound

Copy link
Copy Markdown
Member

Description of Change

WebContents' JS _init registered listeners on itself only to re-emit with data C++ already had. Those are now emitted where they originate: console-message (with the deprecated positional args), unresponsive (when not ignored/hidden/uninitialised), app login / render-process-gone (plus the logging hint), the owner window's ready-to-show, the -before-unload-fired veto for non-interactive types, devtools-reload-page → reload, select-bluetooth-device cancellation when nobody listens, and app web-contents-created. Listener order and microtask/nextTick phase are kept as the JS trampoline (always the first listener) produced them.

Two intentional differences: the console-message deprecation warning is given when an old-signature listener is added rather than on its first message, and web-contents-created carries a real Event and is emitted once _init has finished.

No runtime change intended beyond one JS hop less per event; ~90 lines out of lib/browser/api/web-contents.ts.

Checklist

Release Notes

Notes: none

WebContents' JS _init registered listeners on itself whose only job was to
re-emit with data C++ already had: '-console-message' -> 'console-message'
(plus the deprecated positional arguments), '-unresponsive' ->
'unresponsive' (when not ignored/hidden/uninitialised), 'login' and
'render-process-gone' -> app (and a debugging hint when logging is on),
'ready-to-show' -> the owner BrowserWindow, '-before-unload-fired' ->
preventDefault for non-interactive types, 'devtools-reload-page' ->
reload(), 'select-bluetooth-device' -> cancel when nobody listens, and
app 'web-contents-created' at the end of _init. Each is now done where the
event originates, in the order the JS listener (always the first one) gave:
app before the WebContents' own listeners for login/render-process-gone,
the window after the WebContents for ready-to-show, reload() before
'devtools-reload-page'. The 'console-message' deprecation warning is now
given when a listener with the old signature is added rather than on its
first message.
@MarshallOfSound MarshallOfSound added semver/none target/45-x-y PR should also be added to the "45-x-y" branch. labels Sep 15, 2026
@MarshallOfSound
MarshallOfSound enabled auto-merge (squash) September 16, 2026 00:08

@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.

The native forwarding paths still have several observable parity and lifetime issues, primarily around microtask checkpoints between paired emits and re-entrancy through JavaScript. I also left three focused cleanup/convention comments.

OnDeviceChosen("");
return true;
}
return api_web_contents_->Emit(

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.

Please re-check the lifetime after calling the user-overridable listenerCount method. For example, an app can replace webContents.listenerCount with a function that synchronously destroys the WebContents and returns 1. CallMethod runs that JavaScript above, invalidating api_web_contents_ (and potentially the chooser), then this line calls through the dangling pointer. The old code stayed inside api_web_contents_->Emit(), whose callers already guard chooser destruction with a weak pointer.

// defaultPrevented is read after they have run, as Emit() did.
node::CallbackScope callback_scope(isolate, wrapper,
node::async_context{0, 0});
gin_helper::EmitEvent(isolate, app, "login", event_object, wrapper,

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.

This separate EmitEvent drains promise microtasks before the WebContents login listeners run. CallMethodWithArgs creates its own v8::MicrotasksScope(..., kRunMicrotasks), and the outer node::CallbackScope does not defer that checkpoint. If an app listener queues a promise that supplies credentials while a WebContents listener supplies different credentials synchronously, the app callback now wins; previously the nested app.emit() returned to the same webContents.emit() and all remaining listeners ran before the promise.

base::WeakPtr<WebContents> weak_this = GetWeakPtr();
node::CallbackScope callback_scope(isolate, wrapper,
node::async_context{0, 0});
gin_helper::EmitEvent(isolate, app, "render-process-gone", event, wrapper,

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.

This separate app emit also drains promise microtasks before the WebContents listeners. Previously app.emit('render-process-gone', ...) was nested inside the first listener of the ongoing webContents.emit(), so its promise jobs ran only after the remaining WebContents listeners. Here EmitEvent's own kRunMicrotasks scope checkpoints before execution reaches the second emit, reversing that observable ordering.

"information."}));
}
}
if (weak_this)

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.

Destroying the WebContents from an app-level render-process-gone listener now suppresses its own listeners. In the old nested JavaScript emit, destroying the native object did not stop the already-running EventEmitter listener snapshot, so subsequent WebContents listeners still ran. Here weak_this becomes false and skips that half of the event. The saved wrapper can be used for the second JS emit without dereferencing the destroyed native object.

// defaultPrevented is read after they have run, as Emit() did.
node::CallbackScope callback_scope(isolate, wrapper,
node::async_context{0, 0});
gin_helper::EmitEvent(isolate, app, "login", event_object, wrapper,

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.

Forcing the app event first also changes standard EventEmitter ordering. A handler installed with webContents.prependListener('login', ...) previously ran before the internal forwarding listener; now the app handler always runs first. If both handlers call the one-shot callback, this changes which credentials win. Either preserve the actual listener ordering or call out this compatibility change rather than relying on the internal listener having always been first.

void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
auto weak_this = GetWeakPtr();

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.

weak_this is no longer read after the owner check was moved before emission. Please remove this unused snapshot; it performs an unnecessary WeakPtr operation and now misleadingly suggests the post-emit path checks the WebContents lifetime.

@MarshallOfSound
MarshallOfSound merged commit 1636a92 into main Sep 16, 2026
89 checks passed
@MarshallOfSound
MarshallOfSound deleted the perf/native-webcontents-events branch September 16, 2026 01:01
@release-clerk

release-clerk Bot commented Sep 16, 2026

Copy link
Copy Markdown

No Release Notes

@trop

trop Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

I have automatically backported this PR to "45-x-y", please check out #53979

@trop trop Bot added in-flight/45-x-y and removed target/45-x-y PR should also be added to the "45-x-y" branch. labels Sep 16, 2026
@MarshallOfSound

Copy link
Copy Markdown
Member Author

@ckerr Will handle those in a follow up PR 👍 (and before 45-x-y backport lands)

@MarshallOfSound

Copy link
Copy Markdown
Member Author

@ckerr Done in #53981

@trop trop Bot added merged/45-x-y PR was merged to the "45-x-y" branch. and removed in-flight/45-x-y labels Sep 16, 2026
MarshallOfSound added a commit that referenced this pull request Sep 23, 2026
- The electron_common_environment binding has had no caller since the
  forwarded WebContents events moved native (#53975).
- Nothing requests the electron_browser_printing binding;
  webContents.getPrintersAsync() calls GetPrinterListAsync() directly.
- features.isExtensionsEnabled(), the top-level executeInWorld/
  exposeAPIInWorld exports on the context_bridge binding,
  webFrameMain._fromIdIfExists/_fromFtnIdIfExists,
  WebContents._getPreloadScript, webFrame._isEvalAllowed and
  Menu._getUserAcceleratorAt are not used by lib/ or spec/.
- Protocol::IsProtocolHandled was installed on the prototype template and
  then unconditionally replaced by the JS implementation in
  lib/browser/api/protocol.ts, so the C++ copy could never run.
MarshallOfSound added a commit that referenced this pull request Sep 23, 2026
…es (#54229)

* build: remove unused and duplicated sources from chromium_src

- global_accelerator_listener{,_linux}.cc were compiled here and again by
  the //ui/base/accelerators/global_accelerator_listener dep; keep the dep
  (as a public_dep, shell/ includes its header) and drop the copies.
- native_window_tracker_aura duplicates //ui/native_window_tracker, which
  is already linked; //ui/views/native_window_tracker.h no longer exists.
- chrome's platform_util{,_aura,_mac} were added for the colour chooser
  in 2018 and nothing includes chrome/browser/platform_util.h any more.
- browser_theme_pack, custom_theme_supplier and window_frame_util.cc only
  reference each other; theme_properties and window_frame_util.h stay.
- back_to_tab_label_button, skip_ad_label_button, resize_handle_button
  and overlay_window_live_caption_button are never constructed on desktop
  or sit entirely inside our #if 0 hunks.
- scoped_picture_in_picture_occlusion_observation, predictors_features
  (+ its proto dep), exclusive_access_bubble_type.cc and the spellcheck
  language policy handlers have no callers in anything Electron builds.
- delegated_source_list_capturer is only used by thumbnail_capturer_mac,
  printing_service.cc only by pdf_to_emf_converter (Windows), and the
  hang_crash_dump.cc Linux stub is never called.
- web_request_resource_type.{cc,h} moved upstream in June; the
  enable_electron_extensions=false branch could not gn gen with it listed.

* refactor: remove unregistered browserAction/pageAction extension classes

browser_action.json is not part of the function registration target, so
the twelve BrowserAction*Function and seven PageAction*Function classes
were never instantiated, and the ExtensionActionAPI keyed service was
never built because nothing referenced its factory. Drop them together
with a few other extension leftovers that have no callers:
ElectronExtensionSystem::OnExtensionRegisteredWithRequestContexts,
ElectronExtensionsBrowserClient::SetAPIClientForTest and
ElectronExtensionsRendererClient::AllowPopup (its upstream virtual is
gone), and use extensions::util::AllowFileAccess instead of two local
copies of it.

* refactor: remove unreferenced C++ from shell/

None of these have a caller on any platform:

- OffScreenRenderWidgetHostView::AddGuestHostView/RemoveGuestHostView/
  RemoveViewProxy and guest_host_views_ (never populated, so every loop
  over it was dead too)
- FileSelectHelper::IsAcceptTypeValid/GetSanitizedFileName/
  SetFileSelectListenerForTesting
- FileSystemAccessPermissionContext::OriginHasReadAccess/WriteAccess
- ElectronBrowserClient::GetSiteInstanceFromAffinity
- ElectronPermissionManager::HasPermissionRequestHandler
- api::BaseWindow::SetGTKDarkThemeEnabled and the NativeWindow virtual
  behind it (NativeWindowViews keeps its own private helper)
- crash_reporter::IsCrashReporterEnabled/GetGlobalCrashKeys
- InspectableWebContents::GetDelegate
- NativeWindowObserver::WillCreatePopupWindow/WillNavigate
- WebRequest::RequestFilter's three-argument constructor
- declarations with no definition: ServiceWorkerContext::
  StopWorkersForScope, WebContents::OnElectronBrowserConnectionError/
  OnGetZoomLevel, NetworkContextService::CreateNetworkContextParams,
  WindowsToastNotification::ShowInternal, ElectronApiServiceImpl::
  ProcessPendingMessages
- NativeWindow::is_closed(), WebContentsZoomController::
  persist_zoom_mode(), BrowserProcessImpl::CreateGlobalFeaturesForTesting()
- the Linux stubs for asar::Archive::HeaderIntegrity/RelativePath and the
  non-mac Clipboard::ReadFindText stub (their callers are already
  platform-guarded, so guard the declarations instead)
- the 'render-view-deleted' event, which existed for the removed remote
  module's object registry

* refactor: remove unused gin_helper and converter code

- gin_helper::ErrorThrower::ThrowReferenceError/ThrowSyntaxError, the
  zero-argument PromiseBase::Reject() and PromiseBase::RejectPromise had
  no callers.
- CreateDataPropertyCallback and Dispatcher::DispatchToCallbackForProperty
  were never instantiated.
- Converter<blink::mojom::Referrer> (Electron uses content::Referrer) and
  Converter<blink::mojom::MenuItem::Type>::ToV8 had no users; drop the
  full popup_menu.mojom.h include from content_converter.h and only pull
  the ReferrerPolicy enum into blink_converter.

* refactor: remove native bindings and methods that JS never calls

- The electron_common_environment binding has had no caller since the
  forwarded WebContents events moved native (#53975).
- Nothing requests the electron_browser_printing binding;
  webContents.getPrintersAsync() calls GetPrinterListAsync() directly.
- features.isExtensionsEnabled(), the top-level executeInWorld/
  exposeAPIInWorld exports on the context_bridge binding,
  webFrameMain._fromIdIfExists/_fromFtnIdIfExists,
  WebContents._getPreloadScript, webFrame._isEvalAllowed and
  Menu._getUserAcceleratorAt are not used by lib/ or spec/.
- Protocol::IsProtocolHandled was installed on the prototype template and
  then unconditionally replaced by the JS implementation in
  lib/browser/api/protocol.ts, so the C++ copy could never run.

* chore: remove dead code and stale typings from lib/

- WebFrameMain.prototype._sendInternal, WebViewImpl.setupEventProperty/
  on/onAttach, the 'setLayoutZoomLevelLimits' webview method (removed in
  Electron 9) and WEB_VIEW_ATTRIBUTES.NAME had no callers.
- The Electron 20 sandbox-default deprecation log could never fire:
  getLastWebPreferences() never contains 'preload' and always contains
  'sandbox'.
- lib/browser/api/crash-reporter.ts only ships in the browser bundle, so
  its process.type checks were constant.
- WebSQL was removed in Electron 31; drop enableWebSQL from the inherited
  guest preferences and the docs, and the no-op 'webSQL' clearData type.
- Drop typings for things that no longer exist (ProcessType, ReplyChannel/
  _replyChannel, the WebContents '-ipc-*' and '-window-visibility-change'
  overloads, ElectronInternal.LoadURLOptions, Chrome.Tabs, NodeJS.Global
  augmentations, Process.log/mainModule/_serviceStartupScript, the
  document-start/end overloads, NetBinding.Net/net, App: Function,
  Window.ELECTRON_*_SECURITY_WARNINGS, _awaitNextLoad) and the .oxlintrc
  globs for lib/preload_realm and lib/sandboxed_renderer.

* chore: remove orphaned fixtures, scripts and CI leftovers

- spec/fixtures/release-notes/ (its spec left with the release scripts in
  #52100), devtools-extensions/bad-manifest/, assets/osr.png,
  pages/storage/web_sql.html, pages/history.html, module/hello-child.js,
  esm/local.mjs and api/local-ai-handler/no-language-model.js are not
  referenced by any spec.
- script/verify-chromedriver.py and script/run-if-exists.js lost their
  last callers with the AppVeyor removal; script/lib/npm.py,
  script/lib/native_tests.py, build/args/native_tests.gn, the pyyaml DEPS
  entry and shell/browser/ui/{accelerator_util_unittests,run_all_unittests}.cc
  are leftovers of the native test target removed in #40190.
- script/lib/git.py is_repo_root/get_repo_root and script/lib/utils.js
  getCurrentBranch/handleGitCall have no callers.
- pipeline-electron-build-and-test-and-nan.yml is not referenced by any
  workflow since #49072.
- Three spec/disabled-tests.json titles, one node-disabled-tests entry, a
  wayland allowlist entry, a sysroots.json arch and two CODEOWNERS paths
  named things that no longer exist; four docs/images files are unlinked.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

46-x-y merged/45-x-y PR was merged to the "45-x-y" branch. semver/none

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants