Skip to content
CefSwift
Esc
↑↓navigate↵open⌘Jpreview
On this page

Tab discarding and sessions

Put background tabs to sleep, follow page lifecycle and energy, and restore windows after a quit or a crash.

import CefChromium

let strip = CefProfile.default.tabs
if let session = strip.previousSession, case .clean = session.exit {
    try await strip.restorePreviousSession()
}
try await page.discard()   // frees the renderer; the page reloads when shown

Gallery: DiscardDemo. Browser example: Features/TabDiscarding is Memory Saver: tabs sleep after a while or under memory pressure.

Discarding pages

A page the user is not looking at can give back its memory while staying in your UI. Discarding ends the page’s renderer process; the page keeps its url, title and favicon, and loads the page again as soon as it is shown, navigated or used. isDiscarded is observable, so a tab can fade while it sleeps:

Image(nsImage: page.favicon ?? fallbackIcon)
    .opacity(page.isDiscarded ? 0.4 : 1)

CefKit provides the capability; when to use it is your app’s policy. CefKit never discards a page on its own:

do {
    try await tab.discard()
} catch .blocked(let blockers) {
    print("kept loaded:", blockers)          // [.visible], [.playingAudio], …
}

A policy such as “sleep tabs hidden for an hour, and every hidden tab when memory is low” takes a timer, a DispatchSource.makeMemoryPressureSource, and how long each page has been hidden, which lifecycle and lifecycleChangedAt tell:

for page in CefRuntime.shared.pages
where page.lifecycle == .hidden && .now - page.lifecycleChangedAt > .seconds(60 * 60) {
    try? await page.discard()
}

The Browser example’s Memory Saver (Examples/Sources/Browser/Features/TabDiscarding) is a complete one, with exemptions left to the app: a tab the user pinned is never passed to discard().

Only a page that is off screen can be discarded: a window tab that is not selected, a hidden or minimized window, or a CefWebView that is hidden or out of a visible window. discardBlockers() lists what keeps a page loaded, and discard() throws CefPage.DiscardError.blocked with the same set:

Blocker When
.visible The page is on screen.
.exempt Chromium protects the tab: an extension, pinning, or a setting or enterprise policy.
.notLoaded The page is not open yet, is loading, or shows DevTools itself.
.playingAudio The page plays sound, or did in the last minute.
.capturingMedia The page uses the camera, microphone or screen capture, or is cast.
.formInteraction The user typed into the page or changed its form fields.
.beforeUnloadHandler A frame of the page, the main one or an iframe, has a beforeunload listener or onbeforeunload handler.
.devToolsOpen The page’s DevTools window is open.
.downloading A download it started is in progress.
.pictureInPicture, .connectedToDevice Picture in picture; a Bluetooth or USB device.
.unknown(reason) CefKit could not tell: a check failed or timed out, Chromium gave a reason CefKit does not know, or Chromium cannot tell this tab from another with the same address and title.

A page that is shown, starts loading or navigates while it is being discarded stays loaded, and discard() throws.

Every blocker but .beforeUnloadHandler is something Chromium or CefKit knows natively; that one reads the page’s listeners through the DevTools Protocol, and no check reads the page’s content. Chrome-style pages get Chromium’s own discard rules, which cover audio, form input, picture in picture and devices in every frame. A CefWebView page gets audio and form input from where Chromium’s rules read them, its performance manager: sound from any frame, media element or Web Audio (a muted element does not count) now or in the last minute, and form fields the user changed or text they typed. It never reports .exempt, .pictureInPicture or .connectedToDevice. The facts come from Chromium’s internal chrome://discards page in a hidden service host, which starts on the first check (0.2 to 1.5 s) and closes 30 seconds after the last; while it runs a check takes about a millisecond. If a CEF update changes that page’s interface, the check reports .unknown and the page stays loaded.

.beforeUnloadHandler is asked of the DevTools Protocol in both runtime styles, for every frame, since Chromium runs beforeunload in each: a listener added or removed after load, window.onbeforeunload, and handlers in same-site and cross-site iframes all count. It is asked last, only when no other blocker applies, so a page that is visible, playing audio or holding form input is never asked, and a set with another blocker may lack .beforeUnloadHandler. Asking attaches the page’s DevTools session if nothing else had (see Compatibility with bot protection); it enables no domain and takes a few milliseconds. CEF keeps a session attached until the page closes, or is discarded by closing it, and has no call to detach it, so a policy that polls hidden tabs leaves attached only those that got that far.

discard() itself could find beforeunload natively in a CefWebView, by closing the Chromium page without forcing it and answering “stay” when the page asks, but that runs the page’s beforeunload handlers while it is hidden, which Chrome’s own discarding never does and a page can observe; so it uses the same checks as discardBlockers().

restore() loads a discarded page at once, even while it is hidden. The delegate hears pageWillDiscard(_:), while the page can still be read, then pageDidDiscard(_:), and pageDidRestore(_:) when the page starts loading again. discardSnapshot is an image of the page taken just before it was discarded, for a tab preview or to show while it loads.

What a discard keeps:

CefWindow, Chrome UI windows CefWebView
URL, title, favicon, zoom, profile, delegate Kept Kept
Back/forward list Kept Starts again from the current page
Scroll position Restored Lost
Form input not yet submitted Lost Lost
Bridges and user scripts Work as before Installed again
devTools event streams Keep delivering Keep delivering; enabled domains are enabled again
Other DevTools session state Kept Lost (overrides, scripts added through devTools)
identifier Kept A new one
Offscreen accessibility tree — Emptied, and built again when the page loads

A Chrome-style page is discarded by Chromium itself and comes back when its window is shown. A page in a view is discarded by closing its Chromium page and creating a new one in the same view; it stays in CefRuntime.shared.pages meanwhile. Quitting with discarded pages needs nothing special.

Lifecycle and energy

page.lifecycle says whether the user can see a page and whether it has their input, following the web’s Page Lifecycle. It is observable, and the page’s document.visibilityState agrees with it:

lifecycle visibilityState When
.active visible, and document.hasFocus() On screen, in the key window of the active app, with focus in the page’s view
.passive visible On screen without focus
.hidden hidden Its window is covered, minimized or ordered out, the app is hidden, its tab is not selected, or its view is hidden or out of a window
.discarded — Discarded to free memory
Text(page.title)
    .foregroundStyle(page.lifecycle.isVisible ? .primary : .secondary)

A hidden page draws nothing and runs no animation frames, in every kind of host: for a page in one of your views, CefKit hides Chromium’s view while its window is minimized or ordered out or the app is hidden, which Chromium does not notice by itself. You do not need to do anything for it. Chromium also keeps App Nap off for your app and watches memory pressure and sleep itself.

CefRuntime.shared.energyPolicy lowers offscreen pages to 30 frames a second while Low Power Mode is on or the Mac reports serious thermal pressure, which roughly halves the CPU time an animated page takes. Turn it off for content that must stay smooth:

CefRuntime.shared.energyPolicy = .disabled
CefRuntime.shared.energyPolicy = CefRuntime.EnergyPolicy(reducedOffscreenFrameRate: 45)

Windowed and Chrome-style pages draw at the display’s rate in any case.

Chromium’s main-thread work runs in your app’s run loop through Chromium’s own message loop, as in Chrome: Chromium wakes the main thread when work arrives or one of its timers is due, and not otherwise, also during menus, window drags and modal sessions. Start the runtime before the app’s run loop (CefSwiftApp does; an AppKit app calls CefRuntime.shared.initialize(configuration:) in main, before NSApp.run()), and -[NSApplication stop:] ends run() as usual. A runtime started later, from inside a running app, still works, but its app’s outermost loop no longer ends with stop:.

Configuration.messageLoop = .external uses CEF’s external message pump instead, which an app whose run loop CefKit must not wrap can choose. It polls: each call waits up to 10 ms for work due within that time, and since CEF does not report the timers Chromium’s main thread sets for itself, CefKit also looks for due work on its own, 30 times a second for a quarter of a second after each request, then every energyPolicy.idleMessageLoopInterval (250 ms), so such a timer can run that late. In the Browser example with 16 tabs that keep changing their titles, the browser process took about 35 % of a core with it, against 22 % with Chromium’s loop; idle, 0.7 % against 0.4 % (design notes):

var configuration = CefRuntime.Configuration()
configuration.messageLoop = .external
CefRuntime.shared.energyPolicy.idleMessageLoopInterval = nil  // look 30 times a second

Restoring tabs and sessions

Chromium keeps what closed, newest first, with each tab’s history: strip.recentlyClosed lists it (tabs, windows and groups, with tabCount, closedAt, and for a tab its windowID and index), and strip.reopen(item) brings one back as Chromium closed it: a tab in its window at its place, a window with all its tabs and groups. The page is a new CefPage, with its back and forward history. reopenClosed(in:) is ⌘⇧T: the newest entry. Closing tabs updates the list; call refreshRecentlyClosed() before showing it to be sure.

import CefChromium

let strip = CefProfile.default.tabs
for item in await strip.refreshRecentlyClosed() where item.kind == .window {
    print("Window of \(item.tabCount) tabs, closed \(item.closedAt?.formatted() ?? "-")")
}
if let tab = strip.recentlyClosed.first(where: { $0.kind == .tab }) {
    let window = try await strip.reopen(tab)
    print(window?.tabs.count ?? 0)
}

After a relaunch. CEF restores nothing by itself at startup. Chrome’s session.restore_on_startup is not acted on, and after a crash Chromium lists nothing from the previous run and shows no “Restore pages?” bubble. CefChromium keeps the facts instead: strip.previousSession says how the previous run of the app ended (.clean after the app’s quit, .crashed otherwise) and which windows and tabs it had, and restorePreviousSession() opens them again. After a clean quit they come back as Chromium closed them, history, groups and pinning included: the app’s quit closes each of Chromium’s windows as a window (which Chromium records whole) before CefKit closes the rest. After a crash only the tabs’ addresses and pinning are left (keepsHistory is false), which CefChromium saves as the windows change. Restored windows reach onWindowOpened like any other, so the app’s views go on them. So the app decides: restore at launch, ask in its own interface, or ignore it (discardPreviousSession()):

import CefChromium

let strip = CefProfile.default.tabs
if let session = strip.previousSession {
    switch session.exit {
    case .clean:
        try await strip.restorePreviousSession()
    case .crashed:
        print("Reopen \(session.windows.count) windows?")  // ask in the app's own UI
    }
}

Incognito profiles have no previous session. The Browser example’s Settings › On startup restores after a quit; after a crash it opens a new window and a small prompt to reopen the others.

Discarding

CefPage.discard() frees a hidden page’s document and keeps the CefPage. How depends on the runtime style.

A Chrome-style page is a tab in a Chromium tab strip, so Chromium discards it. CefKit starts Chromium with the WebContentsDiscard feature, which discards a tab in place: the frame tree is torn down and the renderer process exits once no other frame uses it, while the WebContents and its navigation entries stay, marked to load again. Without the feature Chromium replaces the WebContents with a new one, which CEF reports as the page closing and another opening.

Chromium’s own policies (Memory Saver, urgent discarding under memory pressure) never pick a CefWindow’s tab. Each such page is the only, and so the active, tab of its own Chromium window, and the discard eligibility policy protects the active tab of every window, as it does a tab with DevTools attached, which CefKit’s DevTools connection counts as. The EXTERNAL discard reason, which chrome.tabs.discard() uses, skips those protections. CefKit calls DiscardById with it on the discards.mojom.DetailsProvider of the default profile’s chrome://discards service host, after its own checks. It reads Chromium’s other protections (audio, media capture, form interaction, connected devices) from GetTabDiscardsInfo as blockers, leaving out the ones it overrides (active tab, DevTools attached, recently visible, URL scheme, notification permission, an earlier discard attempt); a reason it does not know is a blocker, .unknown(reason), as is a check that fails or times out.

TabDiscardsInfo (Chromium 156) carries a tab’s last committed URL, its title and an id that GetTabDiscardsInfo numbers from 1 on every call; nothing in it, such as a process or frame identifier, maps to a CEF page. CefKit therefore takes a page’s tab to be the one tab with its address or, when several share it, the one that also has its title, and treats any other outcome as a blocker. The look-up, the check of that tab’s protections and visibility, and DiscardById run in one call on the service host, so the tab discarded is the tab just checked. CEF’s frame count for a page drops to zero when Chromium discards its tab; if another of CefKit’s pages loses its frames instead, the discard reloads it and fails.

discard() records the page’s navigation generation (counted at each main-frame load start) and address before its checks. After the checks, and again after pageWillDiscard(_:) and the snapshot, immediately before unloading, it checks the page is still hidden, idle and on the same document, and stops otherwise. chrome.tabs, which the bookmarks host also has, numbers tabs stably and discards with the same reason, but reports none of the protections other than audio, so discarding stays on chrome://discards.

When the window is shown again, Chromium loads the tab (NavigationController::SetActive), with its scroll position from the saved page state. A command sent to a hidden discarded tab reloads it. The DevTools session survives the discard, so bridges, user scripts and event streams carry on unchanged.

An Alloy page is not a tab, and Chromium has no lifecycle unit for it. CefKit closes the Chromium page and keeps the CefPage in CefRuntime.pages without an identifier. When its view is shown again, or the page is used, a new Chromium page is created in the same view. It always starts on about:blank and is set up before it navigates to the saved address: CefDevTools enables again the domains enabled before, so event streams keep delivering; the accessibility state is applied; the attachments’ pageDidRestore(_:) runs (a passkey controller sets itself up again there); user scripts (scripts added with addUserScript included) and bridges are installed, as for a new page. Calls that wait for the restore resume when that page starts loading, and pageDidRestore(_:) follows. Its back/forward list starts from that page. Closing a page never ends a renderer process another browser shares; Chromium keeps the process until its last frame goes.

An Alloy page’s blockers come from its own state (on screen, loading, DevTools, downloads, media capture from on_media_access_change), the beforeunload listeners the DevTools Protocol reports for every frame (CefBeforeUnloadListeners, as for Chrome-style pages), and, for audio and form input, Chromium’s performance-manager graph. CEF’s API has no audible state short of an audio handler, which takes the audio over, and nothing about form input. The performance manager keeps a PageNode for every WebContents, Alloy-style ones included, with the facts Chromium’s own discard rules (DiscardEligibilityPolicy) use: IsAudible (from the WebContents’ audio stream monitor, so any frame, media element or Web Audio, but not a muted element), when audibility last changed, and HadFormInteraction and HadUserEdits, which Blink reports per document. CefPageGraph reads them through discards.mojom.GraphDump, the interface behind the Graph view of chrome://discards, on the same service host as tab discarding. Its module subscribes once per host document (SubscribeToChanges) and keeps each frame node’s page id and frame token from the FrameInfo descriptions. CEF’s frame identifier is "<render process id in hexadecimal>-<frame token>", so a page’s document is the page of the frame node whose token is its main frame’s, with no address or title matching. Each check asks for that page’s current description (RequestNodeDescriptions) and reads PageNodeImpl‘s is_audible, audible_change_time (sound within the last minute counts, Chromium’s kTabAudioProtectionTime), had_form_interaction and had_user_edits. A missing node, a missing field or an unreadable time is .unknown, so a Chromium change keeps pages loaded instead of losing them, and SelfTest’s discard blockers (view) checks fail. With the host running a check takes about a millisecond; the first starts the host (0.2 to 1.5 s measured), which closes after the service hosts’ idle timeout as for any call. Picture in picture, devices and exemptions are not reported for Alloy pages.

The graph also describes has_nonempty_beforeunload on frame and page nodes, but nothing in Blink sets it: it stayed false with listeners in the main frame and in subframes, in both runtime styles. So beforeunload stays with the DevTools Protocol. getEventListeners lists only the listeners of the context its object belongs to, so each frame’s window is reached in that frame’s main world; a cross-site frame lives in another renderer and is reached in a flat session attached for the check. CEF’s typed DevTools callbacks do not handle messages carrying a sessionId, so CefDevTools takes them in on_dev_tools_message: a reply completes its call, an event is dropped rather than delivered as the page’s own session’s.

The library has the capability, not a policy: nothing in CefKit discards a page unasked. The lifecycle coordinator restores a discarded page when it comes on screen (a new Chromium page for one discarded by closing it; a reload, after a moment, for a Chrome-style tab that Chromium has not loaded by itself). When to discard is the app’s: CefPage.lifecycle and lifecycleChangedAt tell how long a page has been hidden, and DispatchSource.makeMemoryPressureSource reports memory pressure. The Browser example’s Memory Saver (Examples/Sources/Browser/Features/TabDiscarding) builds the usual policy from those.

Lifecycle

CefLifecycleCoordinator turns window, app and system signals into what Chromium is told, and publishes CefPage.lifecycle. It listens for window occlusion, miniaturizing, key-window and first-responder changes (firstResponder is key-value observable), app hiding and activation, screen changes, screen sleep, thermal state and Low Power Mode, and updates every page once per run-loop turn.

What Chromium does by itself decides what is left to do. Measured with an animated page and document.visibilityState:

Host Window covered Minimized Ordered out, or a tab not selected App hidden
Alloy, in an app’s view Hidden by Chromium Stays visible Stays visible Stays visible, 60 frames a second
Chrome style (CefWindow) Hidden by Chromium Hidden by Chromium Hidden by Chromium Hidden by Chromium
Offscreen Hidden by the view (was_hidden) Same Same Same

was_hidden does nothing for windowed pages in CEF 156. For an Alloy page in an app’s view, the coordinator hides Chromium’s NSView whenever its window cannot be seen (its occlusion state is not visible, or it is minimized or ordered out, or the app is hidden), which Chromium’s WebContentsViewCocoa reports as hidden. Covered windows are included: Chromium notices a window of the same session covering it, but not a full-screen app on another space, and it reports the page visible again whenever its view moves or shows. The coordinator gives focus back to the responder that had it when it shows the view again, and shows it on willUnhide, before the windows return. With the app hidden, an animated page then takes 2% of a CPU core instead of 23%.

An offscreen view that could not be seen when it asked for its page told nobody, since the page did not exist yet, and Chromium creates offscreen pages visible; a new page starts hidden when its host last reported so.

The lifecycle is derived the way Chromium decides visibility: hidden unless the window is visible, unminimized and not covered (occlusion state), the host view is in it and not hidden, and Chromium’s view is in a window; active when, in addition, the app is active, the window is key and the first responder is the page’s view or inside it.

Chromium handles the rest itself. It listens for memory pressure and system sleep in every process, and sets NSAppSleepDisabled, which keeps App Nap off for the app: with the app hidden, a 50 ms main-thread timer fires within 12 ms of its time over 25 s, with or without a page playing audio. CefKit holds no activity assertion. Page.setWebLifecycleState with frozen fires the page’s freeze event and stops timers set before it, but a timer added later kept running, and a hidden page with busy timers took more CPU frozen than not; CefKit offers no freezing.

Energy. While Low Power Mode is on or the thermal state is serious or critical, CefRuntime.energyPolicy caps offscreen pages’ frame rate (set_windowless_frame_rate) at 30. An animated offscreen page takes about 30% of a core at 30 frames a second and 50% at 60. A rate below the one a page was created with does not hold by itself: every few seconds Chromium paints at the creation rate again while get_windowless_frame_rate still reports the lower one, so the coordinator sets the reduced rate again twice a second while it applies. Windowed and Chrome-style pages draw at the display’s rate, which CEF cannot change.

Tab discarding: the capability, not a policy

CefKit discards a page only when asked (CefPage.discard()) and restores it when it is shown or used. An earlier design also had a runtime-wide discardPolicy with a timer, memory-pressure handling and a per-browser exemption; how long a tab may stay hidden, what counts as memory pressure and which tabs are exempt are product decisions, so they moved to the Browser example (Features/TabDiscarding), built from lifecycle, lifecycleChangedAt, discard() and Dispatch’s memory pressure source.

Audio and form input for Alloy pages

Chromium’s tab rules on chrome://discards were taken to cover only Chrome-style tabs, so the first version read a CefWebView page’s main frame by script (<audio>/<video> playing, <input>/<textarea> edited). That missed other frames, Web Audio and contenteditable, and read the page; it was removed, and for a while Alloy pages reported neither blocker. Page scraping is a last resort, so the native routes were tried first, each against the official CEF 156.0.28 (Chromium 156.0.8078.88) with SelfTest probes:

  • Performance-manager graph: used, for both facts. Chromium’s performance manager (components/performance_manager) has a PageNode for every WebContents, and the probe found CEF’s Alloy-style ones among them (PageNodeImpl type kTab). A page node carries what DiscardEligibilityPolicy decides with: IsAudible() (from WebContentsObserver::OnAudioStateChanged, the AudioStreamMonitor), the time it last changed, and HadFormInteraction() and HadUserEdits(), aggregated over frames from what Blink reports through DocumentCoordinationUnit. chrome://discards exposes the graph as discards.mojom.GraphDump (DiscardsGraphDumpImpl): SubscribeToChanges(GraphChangeStream) streams FrameCreated, PageCreated, the …Changed events and NodeDeleted, each with JSON from the node data describers (PageNodeImplDescriber, FrameNodeImplDescriber), and RequestNodeDescriptions(ids) describes nodes as they are now. A FrameNodeImpl description has frame_token, the second half of CEF’s frame identifier, whose first half is the render process id in hexadecimal ("6-7BDA0EC0…" and "7BDA0EC0…"), so a page’s document is found exactly from its main frame. In the probe an audio element, Web Audio and a page muted with set_audio_muted were all is_audible: true (muting the page does not make the page silent, as in Chrome); a playing <video muted>, and a page whose play() was refused for want of a gesture, false; a page paused a second earlier false, with audible_change_time: "0 hr, 0 min, 1 sec"; a text field typed into with Input.insertText had both had_form_interaction and had_user_edits. A description request took 0.3 to 2 ms in the host’s renderer. CefPageGraph reads it.
  • chrome://discards tab list: works, not used. GetTabDiscardsInfo lists Alloy pages too, contrary to what the first version assumed, with “Tab is playing audio”, “Tab has recently played audio”, “Tab has form interactions” and “The user has edited the tab’s content” where they apply. Its entries carry only address, title and a per-call id, so two views on one page could not be told apart; the graph’s frame token tells them apart, so the tab list stays for Chrome-style tabs, where its id is what DiscardById takes.
  • chrome://media-internals, chrome://process-internals: not suitable, and not probed further once the graph worked. Media internals reports players and audio streams per render frame through WebUI messages (chrome.send) rather than Mojo, identifies them only by process and frame routing ids, and has nothing on forms. Process internals (process_internals.mojom) describes frame trees and site isolation; the probe could not import its bindings from strings.m.js and it was not pursued, since it has neither fact.
  • CEF C API and AppKit: no signal. cef_browser_host_t has set_audio_muted/is_audio_muted (the mute switch, not whether sound plays); cef_display_handler_t::on_media_access_change is capture, which .capturingMedia already uses; cef_audio_handler_t reports streams only by taking the audio output over, which a check must not do. Nothing in cef_frame_t, cef_browser_t or the context menu parameters reports form state. Chromium’s NSView does not use NSUndoManager for web editing (undoManager.canUndo stayed false after typing) and leaves NSWindow.isDocumentEdited unset. The offscreen accessibility tree has field values but not whether the user changed them, and nothing on audio; reading it would be reading the page.
  • DevTools Protocol: partial. Media.playerPropertiesChanged reports media element players (codec, tracks, frame URL) when Media.enable precedes playback, but no audible state, nothing for Web Audio (the WebAudio domain gives a context’s state, not its output) and it needs a session from page load on. No domain reports form interaction without reading the DOM.
  • CefRenderer: no route. CEF’s renderer API reaches V8 contexts and process messages, not Blink’s media or editing state; what it could learn it would learn by running in the page, the scraping this avoids.
  • Script scan: not needed. It stays the last resort should a CEF update remove GraphDump; until then such a change reports .unknown.

The graph is Chromium-private: its JSON is unversioned, and chrome://discards could drop the interface. A missing node or field, or an unreadable time, is .unknown(reason), never a page safe to discard, and SelfTest’s discard blockers (view) checks (a quiet page reports nothing, an audible one exactly .playingAudio) fail on the first CEF update that changes it. The cost is the chrome://discards host’s renderer, shared with tab discarding, while checks are made, the graph’s change stream into it meanwhile, and about a millisecond per check (0.2 to 1.5 s for the first, which starts the host); the host closes after the usual idle timeout.

beforeunload stays with the DevTools Protocol

The page graph describes has_nonempty_beforeunload, on each frame node’s document and on the page node, which looked like a way to drop the DevTools Protocol from discardBlockers(). A SelfTest probe against CEF 156.0.28 read it for both runtime styles (CefWebView and CefWindow) through every case that matters: a listener added after load and removed again, window.onbeforeunload set and cleared, two listeners with one removed, a listener in a same-site iframe and in a cross-site one (out of process), at load and added after it. The field was false every time, on every frame and on the page, while the DevTools Protocol saw each listener. Chromium’s source fits: FrameNodeImpl::SetHasNonEmptyBeforeUnload is only the receiving end of DocumentCoordinationUnit, and Blink’s DocumentResourceCoordinator has the sender, but LocalDOMWindow, LocalFrame and Document do not call it; LocalDOMWindow reports beforeunload listeners only as a sudden-termination disabler to its RenderFrameHost, which neither the graph nor CEF’s API exposes. The CEF C API has nothing either (try_close_browser runs the handlers rather than reporting them), nor has AppKit.

So the blocker stays with the DevTools Protocol, for both styles. The probe found the old check incomplete: it asked only the main frame’s window, and Chromium runs beforeunload in every frame, so a listener in an iframe went unseen. getEventListeners reports only listeners of the context its object belongs to (InspectorDOMDebuggerAgent), so a subframe’s window has to be obtained in that frame’s main world: from Page.getFrameTree, DOM.getFrameOwner, DOM.describeNode (the owner’s contentDocument), DOM.resolveNode and Runtime.callFunctionOn (defaultView). The DevTools frame id is the frame’s DevTools token, not CEF’s frame token, so CEF’s frame list cannot be used for this. A cross-site frame is not in the main session’s frame tree: Target.getTargets lists it as an iframe target with a parentId, and Target.attachToTarget with flatten gives a session in which the same steps work. CEF delivers that session’s messages to on_dev_tools_message but not to its typed callbacks (a reply never arrived until CefDevTools parsed them there), so CefDevTools takes messages with a top-level sessionId there, and drops their events so that listeners never mistake them for the page’s own. A check took 2 to 14 ms measured, subframes included; it enables no domain.

The page node’s PageLiveStateDecorator data was also read, for blockers Alloy pages do not report. It has IsConnectedToUSBDevice, …BluetoothDevice, …HidDevice, …SerialPort, IsCapturingVideo, …Audio, …Window, …Display, IsBeingMirrored, IsAutoDiscardable, IsPinnedTab and IsDevToolsOpen (true in the probe, whose DevTools check had attached a session). None was added: capture is .capturingMedia already, from on_media_access_change, for both styles; mirroring is casting, which CEF does not have; pinning and auto-discardability are Chrome tab-strip state an Alloy page does not have, and its exemptions are the app’s policy; and the device flags could not be checked without a device and a chooser the user answers, so they are not known to be exact for Alloy pages. Picture in picture is not in the graph’s descriptions at all.

Was this page helpful?