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

Layering SwiftUI over and under pages

The page's canvas, title bars in web content, Chromium's AppKit classes and what Chromium draws over a Chrome-style window.

window.setPageOverlay {
    ZStack {
        LinkStatus(page: window.page)   // over the page, never taking its clicks
        MyIndicator(page: window.page)
    }
}

Gallery: ChromiumSurfacesDemo, OffscreenOverlayDemo.

Background

Where a page paints nothing, as before its first paint, behind a page with no background of its own, and in the area a resize uncovers until the page repaints, the page shows its canvas: opaque white, as in Chrome and WKWebView, whatever the app’s or the system’s appearance. A page that opts into a dark color scheme (color-scheme: dark, or light dark while the app’s appearance is dark) gets Chromium’s dark canvas, as in Chrome. The view behind Chromium’s, which shows until its first paint, has the same color, so a page opens without a dark flash.

A Chrome-style page (CefWindow) is the exception: Chromium leaves its page’s canvas transparent and paints the window theme’s web-contents color behind it, which follows the app’s appearance. CefKit sets that color to the canvas color, so unstyled pages stay white, but a dark page with no background of its own shows the canvas color there too.

backgroundColor changes the canvas, in every kind of page. Chromium paints only an opaque canvas, so its alpha is ignored. An offscreen page can be see-through instead, showing what is behind the view, with drawsBackground = false, as WKWebView’s; the page’s own backgrounds still paint:

var overlay = CefPage.Configuration()
overlay.rendering = .offscreen
overlay.drawsBackground = false

Windowed and Chrome-style pages keep an opaque canvas: CEF lets only a page it renders offscreen paint a transparent one.

Title bars in web content

An app whose window chrome is web content, a music player’s or a chat client’s, marks its title bar with the CSS property -webkit-app-region: drag, and its buttons inside it with no-drag, as Electron apps do. page.draggableRegions lists the regions the page declares, in the page’s view points with a top-left origin, and page.isDraggable(at:) says whether a point is in one (the last region that contains it decides). CefWindowedPageView and CefOffscreenPageView move their window when a drag starts in a draggable region, and zoom or minimize it on a double click as the user’s “Double-click a window’s title bar” setting says; the page does not get those clicks. A host view of your own asks isDraggable(at:) and calls NSWindow.performDrag(with:).

let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 900, height: 600),
                      styleMask: [.titled, .closable, .resizable, .fullSizeContentView],
                      backing: .buffered, defer: false)
window.titlebarAppearsTransparent = true
window.titleVisibility = .hidden
window.contentView = CefWindowedPageView(page: page)
header { -webkit-app-region: drag; height: 38px; padding-left: 78px; }
header button { -webkit-app-region: no-drag; }

Chromium’s AppKit classes

The framework exports only CEF’s C API, but Chromium’s macOS UI is AppKit, and its Objective-C classes are visible to the Objective-C runtime. CefObjCHook overrides a few of their methods, a feature at a time: CefChromium’s surface tracking (CefNSWindow and BrowserNativeWidgetWindow child windows, NativeWidgetMacNSWindow alpha), swipe gating (ChromeRenderWidgetHostViewMacDelegate) and the swipe indicator (HistoryOverlayController). Every method a feature overrides or calls is looked up first by class name, selector and type encoding, and the feature’s overrides go in only when all of them are there; one missing method leaves the whole feature out, logged and listed per feature by SelfTest’s “runtime hooks” check, and the feature falls back to Chromium’s own behavior instead of running partly hooked. An override added to a class that inherits the method stays on that class alone.

Surfaces. Chromium’s bubbles, dialogs, find bar and status bubble are Views widgets, each in a NativeWidgetMacNSWindow that Chromium attaches to the CefWindow as a child window. Every CEF Views window is a CefNSWindow, a subclass; CefSurfaceTracker overrides its -addChildWindow:ordered: and -removeChildWindow:. As Chromium attaches a widget, the window’s surface controller makes it transparent; once attached, it reads what the widget shows and applies the kind’s presentation: it restores the widget and moves it under its anchor with setFrameOrigin(_:) (and again when the widget or the window moves or resizes), or keeps it transparent, ignoring the mouse, and closes it as Esc would, or for the find bar with IDC_CLOSE_FIND_OR_STOP. Status bubbles and fullscreen notices are only kept transparent, since Chromium reuses their windows. Chromium fades some widgets in by setting their window’s alpha, the status bubble on every hover, so an override of -setAlphaValue: in NativeWidgetMacNSWindow keeps a hidden surface’s window at 0, and keeps the alpha Chromium asked for, which a reused window gets back when it is shown again.

Two state machines, in ChromiumSurfaceController, replace what was implicit ordering. Each of Chromium’s windows is in a WidgetPhase: attaching (transparent, between -addChildWindow: and its return), recognizing (attached without a view tree yet: transparent, looked at again every 50 ms, six times, then shown as .other("")), shown (a native surface, placed and followed) or suppressed (hidden or replaced, closed natively); it leaves the table when Chromium detaches or closes it, and a suppressed window Chromium attaches again is decided afresh. Each CefChromiumSurface is presented until end(_:_:) makes it dismissed(reason), the one transition out, which also stops its observers and, for a custom find bar, the find session. A policy change moves each presented surface to its kind’s new presentation through the same two paths. Custom surfaces end with what they show: the find bar with CefFindSession.isActive, the status bubble with statusText, the others with a main-frame navigation to another document (observed on CefPage.url), as Chromium’s bubbles close. Closing the window ends every surface (.window) and drops the app’s presenters and callbacks. A zoom command the window replaces is passed on to Chromium, which runs the interceptor again through on_chrome_command in the same turn; that second call is recognized and let through. Print preview takes Esc only in its page, so it is closed by focusing its RenderWidgetHostViewCocoa and pressing Esc until it goes: -[NSWindow close] on it, as on bubbles, ends the browser process.

A widget’s kind comes from the class of the view inside it. Views reports each view’s class name to accessibility as AXDOMClassList, so the tracker walks the widget’s accessibility tree (QRCodeGeneratorBubble, CastDialogView, FindBarView, LoginView, StatusView, SubtleNotificationView, DownloadBubbleContentsView, …). When no class matches, the title is compared with Chromium’s localized strings for each kind, read by identifier from the resource bundle (cef_resource_bundle_t); anything else is .other, with the title or the first specific class name. The QR code bubble’s address comes from its text field’s accessibility value.

Commands that open a surface the window replaces or hides never reach Chromium: CefPage.execute(_:) and the command handler’s on_chrome_command hand them to CefChromium’s command interceptor first. The custom find bar drives CEF’s find/stop_finding and reads on_find_result. A new search only highlights its matches (Chromium reports an active ordinal of 0 and an empty selection), so once its count is final CefFindSession repeats the request, which selects the first match, as Chrome’s find bar does; the custom status bubble reads on_status_message; the Cast picker uses CEF’s cef_media_router_t.

CEF’s own hooks do not cover placement: cef_window_delegate_t and cef_browser_view_delegate_t have no say in where bubbles go, and Chromium anchors them to its toolbar’s buttons. CEF_CTT_NORMAL and CEF_CTT_LOCATION do not change where they appear in a CefWindow, which does not add Chrome’s toolbar view (get_chrome_toolbar) to its window; adding it would draw Chrome’s toolbar.

Swipes. For Chrome-style pages, Chromium sets a ChromeRenderWidgetHostViewMacDelegate on each page’s RenderWidgetHostViewCocoa; its HistorySwiper turns overscrolling two-finger swipes into navigation and draws progress with a HistoryOverlayController. CefSwift overrides the delegate’s -shouldAllowHistorySwiping, to follow allowsBackForwardNavigationGestures, and the controller’s -initForMode:, -showPanelForView:, -setProgress:finished: and -dismiss, to report progress to navigationGestureProgress and to skip Chrome’s overlay unless showsChromiumNavigationGestureIndicator is on. Alloy-style pages have no such delegate; views track swipes themselves with NSEvent.trackSwipeEvent, the offscreen view from its own scroll events and the windowed view from a local event monitor, since Chromium’s view receives the events. CefKit draws no indicator of its own; apps draw one from navigationGestureProgress, over a CefWindow’s page in its pageOverlay, which is a view laid over the content view, clipped to the page and passing every event through.

What Chromium shows over a Chrome-style window

SelfTest’s surface inventory (SELFTEST_ONLY=nativeUI SELFTEST_SURFACE_DUMP=<folder>) triggers about seventy pieces of Chromium’s interface in a CefWindow, with and without Chrome’s toolbar, and records each window that appears (class, size, parent, title, Views classes, kind) and each delegate call CefKit makes instead. On CEF 156:

  • Attached to the window, as Views widgets (what CefChromium follows): find bar, status bubble, zoom bubble, QR code, downloads bubble and its start animation, fullscreen notice (also for keyboard lock), HTTP sign-in (with authenticationPrompt = .chromium), autofill suggestions, USB and serial choosers, the payment sheet, print preview, and, with Chrome’s toolbar, the tab group editor. Before this change the last six were .other with a title or a class name, or .other(""); they now have kinds (.autofillSuggestions, .deviceChooser, .paymentRequest, .printPreview), and what is still unknown (the download animation, the tab group editor) stays .other, observable and hideable.
  • Answered by the delegate, so never Chromium’s UI: every permission request (camera and microphone with fake devices, location, notifications, clipboard, MIDI, window management, protocol handlers, multiple downloads, screen capture), JavaScript dialogs, beforeunload, file choosers, downloads’ destinations, context menus. There is no permission prompt or quiet chip to hide: the delegate path is the only one.
  • Windows of their own, not attached: picture in picture, the task manager, DevTools, the colour panel (a RenderWidgetPopupWindow), <select> menus (native menus), macOS’s share menu; and Chromium’s own browser windows for chrome:// pages it opens (downloads, extensions, settings).
  • Nothing at all: send tab to self, the bookmark, translate, page info and save-password bubbles (with or without the toolbar), the app and avatar menus and the omnibox popup through commands, storage access, a popup blocked without a gesture (not even the delegate hears of it), an external protocol without a handler, the date picker, the crash page (a page).
  • Ends the browser process: IDC_MANAGE_PASSWORDS_FOR_PAGE, with or without the toolbar; CefKit now refuses it.

Bluetooth, HID, screen-capture pickers after a grant, passkey sheets and Cast were not triggered: each would reach a macOS prompt (Bluetooth, Input Monitoring, Screen Recording, Touch ID, Local Network). The full table is the probe’s inventory.md.

Replacement is offered only where the app can get the surface’s content and act on it through CefKit (Kind.capabilities, the guide’s table), not uniformly: CEF has no API for translation, saved passwords, autofill, device choosers, payments or print preview, so those kinds can be observed, hidden and dismissed but not replaced.

Chrome style and a dark page’s canvas

A color-scheme: dark page without a background of its own shows the page’s backgroundColor in Chrome style, where Alloy shows Blink’s dark canvas. Blink paints that canvas only when the frame’s base background is opaque; Chrome style leaves it transparent (the page’s own frame reads transparent) and paints kColorWebContentsBackground behind it, which CefKit sets to backgroundColor. The CEF C API has nothing that sets the base background of a Chrome-style page: cef_browser_settings_t’s background_color does not reach it, cef_view_t.set_background_color colours the view, and the theme colour is what shows through. The DevTools protocol’s Emulation.setDefaultBackgroundColorOverride sets it, which should let Blink paint the dark canvas, but it would keep a DevTools session on every Chrome-style page, which pages can notice (guide); it was not adopted or tried. SelfTest keeps its two limitation skips.

Was this page helpful?