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

CefWebView and AppKit hosts

Show a page in SwiftUI or AppKit: the observable CefPage, loads, PDF, attachments, focus, tooltips and the context menu.

struct Reader: View {
    @State private var page = CefPage(url: URL(string: "https://swift.org")!)

    var body: some View {
        CefWebView(page)
            .navigationTitle(page.title)
            .toolbar {
                Button("Back", systemImage: "chevron.left", action: page.goBack)
                    .disabled(!page.canGoBack)
            }
    }
}

Gallery: ObservableStateDemo, AppKitHostingDemo, PDFDemo, ContextMenuDemo.

Pages

CefPage is the model of one page: an @Observable object with the page’s state and the commands you can send it. Create it, bind views to it, and hand it to a view or window. Chromium creates the underlying page when it is first shown.

Kind Members
State url, title, isLoading, estimatedProgress, canGoBack, canGoForward, favicon, faviconURL, zoomLevel, isFullscreen, statusText, downloads, findResult, mediaCapture (.video, .audio: what the page captures now), draggableRegions (title bars in web content), frames, state (.pending, .live, .closed)
Navigation load(_:) (returns a CefNavigation), goBack(), goForward(), backForwardList, go(to:) (back/forward list), reload(ignoringCache:), stopLoading(), waitUntilLoaded(timeout:) (waiting for a load)
Page isAudioMuted, zoom(_:), canZoom(_:), defaultZoomLevel, exitFullscreen(), replaceMisspelling(with:), learnSpelling(_:), text(of:), source(of:), find(_:backwards:caseSensitive:) (its findResult has the match’s selectionRect), stopFinding(clearingSelection:), findSession (an observable find-bar model), print() (Chromium’s printing, which in Chrome style is Chrome’s print preview, not the system dialog), pdf(configuration:), printToPDF(at:configuration:) (PDF), snapshot()
JavaScript evaluateJavaScript(_:timeout:), evaluateJavaScript(_:as:timeout:), executeJavaScript(_:), addUserScript(_:), removeUserScript(_:)
DevTools devTools, showDevTools(inspecting:), closeDevTools(), isShowingDevTools
Lifetime ready(), close(force:)
Memory isDiscarded, discard(), restore(), discardBlockers(), discardSnapshot, lifecycle, lifecycleChangedAt (discarding)
Relations delegate, configuration, profile, opener, popupFeatures, hostWindow

Options are fixed at creation:

var pageConfiguration = CefPage.Configuration()
pageConfiguration.profile = .persistent(id: "work", displayName: "Work")
pageConfiguration.content.javaScript = .disabled
let page = CefPage(url: URL(string: "https://swift.org")!, configuration: pageConfiguration, delegate: policy)

Most policy belongs to the page’s profile and reaches every page in it, those Chromium opens itself included: request filters, scheme handlers, user scripts, bridges, attachments, permissions and downloads. The page’s configuration adds its own or overrides the profile’s; see What is configured where.

content holds Chromium’s per-page web preferences (cef_browser_settings_t): javaScript, images, webGL, localStorage and webFonts (.automatic or .disabled), clipboardAccess (.automatic, .copy, or .copyAndPaste, which lets the page read the clipboard: for your own content only), fonts (the families for the CSS generic families) and defaultEncoding. A popup Chromium opens gets its opener’s. Font sizes are the profile’s webkit.webprefs preferences: in CEF 156 they win over a page’s own.

CefIOActor runs on Chromium’s IO thread, which carries every request and message between processes: never block it. CefFileActor runs on Chromium’s sequence for blocking work the user waits on, such as reading files.

favicon is the page’s icon as an NSImage, downloaded at up to 32 points from the address in faviconURL. Both are nil until the page reports an icon, and become nil again when a new main-frame document starts loading. For pages that are not open, CefChromium has profile.history.favicon(for:size:).

zoomLevel is 0 for 100%, and each step of 1 scales the page by 20%. You can set it, and it follows the zoom Chromium applies: the level it remembers for each site, restored as the page moves between sites, and Chrome’s zoom commands. CEF does not report zoom changes, so CefKit reads the level back after navigations, zoom commands and changes made through zoomLevel; other changes show up at the next navigation. In a windowed page, pinching magnifies the page without changing zoomLevel. A level set before the page exists applies to its first page, as isAudioMuted set early applies once it exists.

zoom(.zoomIn), zoom(.zoomOut) and zoom(.reset) step through Chrome’s preset factors (90%, 100%, 110%, 125%, …) as the View menu does, and canZoom(_:) says whether a step can be taken, for enabling menu items. defaultZoomLevel is the level a page opens at with no site-specific one. The level stays CEF’s logarithmic one; a factor is pow(1.2, zoomLevel).

exitFullscreen() takes the page out of fullscreen, for an app’s own command: a Chrome-style page leaves on Escape and the window’s green button by itself, an Alloy-style one needs the app to ask.

CefRuntime.shared.securityDisplayString(for:) formats a URL as Chromium shows a site to people deciding whether to trust it: scheme and host only, no default port, and an internationalized domain in Unicode only where that is safe from look-alikes (otherwise Punycode). Use it for an address bar’s security view or a permission prompt, never to parse.

A page holds its delegate weakly, as WKWebView does. Keep a strong reference to the delegate for as long as the page lives; a delegate created inline, as in CefPage(url: url, delegate: Policy()), is released at once and the page falls back to the default decisions.

A page you create lives until you call close(). Unless you pass force: true, the page’s beforeunload handler can ask the user to stay. After state becomes .closed, create a new CefPage to browse again.

Waiting for a load

load(_:) returns the CefNavigation it started. Await it to continue once that page has loaded:

let result = try await page.load(url).waitUntilLoaded(timeout: .seconds(30))
print(result.url as Any, result.httpStatus ?? 0)

waitUntilLoaded(timeout:) on the page waits for whatever it loads now, and returns at once when it has loaded already. It suits a page just created, a reload, or a page that navigates by itself:

let page = CefPage(url: home)
// …once a view or window shows it:
try await page.waitUntilLoaded(timeout: .seconds(30))

CEF gives navigations no identity of their own. The navigation a CefNavigation stands for is the first main-frame navigation Chromium starts as a direct load after load(_:) was called; links, scripts, reloads and history steps do not count as it. Each wait ends in exactly one of these ways:

Outcome What the wait returns or throws
The document committed and its load event ran CefLoadResult: the final url after redirects, the httpStatus
A server redirect, or a script or <meta> refresh navigating before the page finished Part of the same navigation; url is where it ended
Only the fragment differs from the page shown Finishes as the address changes, with isSameDocument set
A network or HTTP-level failure The CefLoadError the delegate’s didFailLoad gets
No new page: a download, a 204 or 205 response, stopLoading(), the delegate cancelling it CefLoadError with isCancellation (ERR_ABORTED)
Another load(_:), a link, a script, back or forward starts first CefError.navigationSuperseded
The renderer crashed while the document loaded (chrome://crash included) CefError.renderProcessTerminated(_:)
The page closed CefError.pageClosed
timeout ran out CefError.timedOut; the navigation goes on
The waiting task was cancelled CancellationError; the navigation goes on

The browser-wide waitUntilLoaded(timeout:) follows a superseded navigation to the one that replaced it, so it ends only when the page has settled; when the last navigation failed, it throws that error, even if the page settled earlier. A page not created yet waits for its first page, and a discarded page is restored first. A load asked of a page that is still being created, setting up or discarded starts once it can, and is not superseded by the page’s own set-up.

PDF

pdf(configuration:) renders the page as PDF data, and printToPDF(at:configuration:) writes it to a file. A CefPage.PDFConfiguration starts from the user’s Page Setup: the paper size of NSPrintInfo.shared, portrait, Chromium’s default margins, backgrounds printed, and a tagged PDF, which assistive apps read in order, with an outline made from the page’s headings.

var configuration = CefPage.PDFConfiguration()
configuration.isLandscape = true
configuration.margins = .uniform(36)                     // points
configuration.pageRanges = [1...2, 5...5]
configuration.footerTemplate = """
    <div style="font-size: 9px; margin: auto">
      <span class=pageNumber></span> / <span class=totalPages></span>
    </div>
    """
let data = try await page.pdf(configuration: configuration)

Sizes and margins are in points. prefersCSSPageSize uses the size a page’s @page rule asks for instead of paperSize; a page whose rule gives a size keeps that size’s orientation whatever isLandscape says. Header and footer templates fill in elements with the classes date, title, url, pageNumber and totalPages; give them a font size, since Chromium sets none. A page range past the last page, or ranges that leave no page, make the call throw.

Attachments

CefPage.Configuration.attachments adds code of your own that sets up every page made with the configuration, and CefProfile.attachments every page of a profile, before the page’s own: objects adopting CefPageAttachment. CefKit tells each one when Chromium has created a page, when a discarded page is created anew, and when a page closes. One attachment serves every page made with its configuration, popups included, since a popup gets its opener’s configuration, so keep what belongs to one page keyed by the page:

final class ConsoleRecorder: CefPageAttachment {
    private var tasks: [ObjectIdentifier: Task<Void, Never>] = [:]

    func pageDidCreate(_ page: CefPage) async {
        let messages = page.devTools.events("Runtime.consoleAPICalled")
        try? await page.devTools.send("Runtime.enable")
        tasks[ObjectIdentifier(page)] = Task {
            for await message in messages { print(message["type"].stringValue ?? "") }
        }
    }

    func pageDidClose(_ page: CefPage) {
        tasks.removeValue(forKey: ObjectIdentifier(page))?.cancel()
    }
}
Member Called
pageDidCreate(_:) async Once Chromium has created the page. Before its first page starts loading only when an attachment preparesBeforeFirstDocument.
pageDidRestore(_:) async Once a page discarded by closing it is created anew; its page loads again after this returns. Domains enabled through devTools are on again by then and event streams go on, but what the old Chromium page held, such as scripts added with Page.addScriptToEvaluateOnNewDocument, is gone.
pageDidClose(_:) When the page has closed, before its DevTools session ends, once, after the other calls. Also for a page that closed before every attachment was told of its creation. Not for a discard.
preparesBeforeFirstDocument false by default. true holds the first page until pageDidCreate(_:) returns.

When an attachment preparesBeforeFirstDocument, the page starts on about:blank and loads its page once every attachment has been told of its creation; ready() waits for that, and DevTools calls and JavaScript the attachment makes meanwhile go through. Without such an attachment, ready() means the page exists and can be used: it does not wait for attachments, which are told of the creation as the page becomes ready, and one of them may still be setting up when ready() returns. After a discard, ready() waits for every pageDidRestore(_:). A native popup cannot be held that way, since Chromium creates it and runs its first document at once. So a popup, tab or window the delegate lets Chromium open (.allowNativePopup) opens instead in a page CefKit creates with the opener’s configuration. It arrives as a native popup does (page(_:didOpen:), then onPopup or a window of its own), but the page cannot script it: window.open returns null, the popup has no window.opener, and a blank popup is refused. Browsers Chromium opens without a page asking, such as a tab from Chrome’s own UI, have the default configuration, so only their profile’s attachments set them up. Passkeys are built this way.

In AppKit

CefWindowedPageView and CefOffscreenPageView are the NSViews CefWebView hosts its pages in. They are in CefKit, so an AppKit app depends on the CefKit product and imports neither SwiftUI nor CefSwiftUI. Pick the view that matches the page’s rendering:

import AppKit
import CefKit

@MainActor
final class BrowserWindowController: NSWindowController {
    let page = CefPage(url: URL(string: "https://swift.org")!)

    init() {
        let window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 1024, height: 768),
            styleMask: [.titled, .closable, .resizable, .miniaturizable],
            backing: .buffered, defer: false)
        super.init(window: window)
        window.contentView = CefWindowedPageView(page: page)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) { nil }
}

Chromium creates the page once its view is in a window. A view never closes its page: call close(force:) when you are done with it. Assigning another browser to page shows that one instead, and moving a live page to another view keeps its document. A page shows in one view at a time: the view it leaves sets its own page to nil, and no longer hosts it, resizes it, forwards input or answers accessibility for it. To draw frames or host a windowed page in a view of your own, see Offscreen rendering and page.host(windowedIn:).

page.stopHosting(in: host) withdraws a page from a host without closing it: a creation waiting for the profile to load is dropped, a windowed page’s native view leaves the host, and an offscreen page stops painting. It does nothing unless host is the page’s current host, so a host that has been replaced cannot take the page from the newer one. Host it again to show it.

Keyboard focus

CefWindowedPageView and CefOffscreenPageView take part in the window’s key-view loop like any control. Tab from the control before the view focuses the page’s first focusable element, Shift-Tab from the control after it the page’s last. Tab past the page’s last element (or Shift-Tab past its first) moves on to the next (or previous) key view outside the page’s view:

nameField.nextKeyView = browserView
browserView.nextKeyView = sendButton

Chromium reports a page giving up focus natively (on_take_focus). It has no call for focusing a page’s first or last element, so entering the page clears its focused element with one blur() in the page’s main world and presses Tab (or Shift-Tab) for it. An offscreen view of your own calls hostViewDidBecomeKey(selecting:) with the window’s keyViewSelectionDirection from becomeFirstResponder().

Tooltips

page.tooltip is the page’s tooltip while one shows: its text (a title attribute’s, which can run over several lines) and the pointer’s location in the host view (top-left origin; Chromium gives no anchor of its own). It is observable, and goes when the pointer moves off, the page navigates, the page closes or is discarded, and, in an offscreen page, when the user scrolls or types or the view loses key status.

page.tooltipPolicy says who shows it:

Policy Offscreen (CefOffscreenPageView) Windowed and Chrome style
.automatic (default) The view’s own toolTip, with AppKit’s look, delay and placement. Chromium’s own tooltip.
.custom Nothing: the app shows page.tooltip. Nothing: on_tooltip answers that the app shows it.

With .custom, draw the tooltip yourself, for example over an offscreen CefWebView, where SwiftUI content can sit above the page; keep it out of hit testing so the page still gets the pointer:

CefWebView(page)
    .overlay(alignment: .topLeading) {
        if let tooltip = page.tooltip {
            Text(tooltip.text)
                .font(.callout)
                .padding(6)
                .background(.regularMaterial, in: .rect(cornerRadius: 6))
                .offset(x: tooltip.location.x, y: tooltip.location.y + 18)
                .allowsHitTesting(false)
        }
    }
    .onAppear { page.tooltipPolicy = .custom }

Only title text comes this way. A page’s own tooltips (a popover, an interestfor target, CSS) are page content and already show in the page; the tooltips of Chromium’s own interface, such as a CefWindow’s toolbar buttons, are Chromium’s. A windowed page’s document is drawn by Chromium’s GPU process into layers SwiftUI’s overlays are placed above; clicks on such an overlay reach it, not the page, but SelfTest cannot read a windowed page’s pixels to check what shows, so for a windowed page prefer a view or window of your own above it. SelfTest measures the offscreen cases; the windowed and Chrome-style ones need the real pointer, which an unattended run does not move.

When the page moves to another host, or stopHosting(in:) withdraws it, the host hears offscreenDidStopHosting(_:): stop calling the page from then on. The new host gets the whole page painted again.

CefOffscreenPageView is the reference implementation.

Context menu

For each right-click, CefKit reads the menu Chromium builds into a CefContextMenu, a value the configuration changes, and shows it the same way in every page, windowed or offscreen, Alloy or Chrome style: as a native NSMenu at the click, with the system’s Services.

With no configuration the menu is Chromium’s, titled in Chromium’s language (CefRuntime.locale):

  • Chrome-style pages (CefWindow) show Chrome’s menu: Open Link in New Tab, New Window and Incognito Window, Save Link As, Copy Link Address, the image, audio and video items, Look Up, Search, Create QR Code, Emoji & Symbols, spelling suggestions, Speech, Writing Direction, Print, View Page Source and Inspect. An item that opens something goes where a page’s request would: a tab or window to page(_:decideWindowOpenFor:), with its disposition (.newBackgroundTab, .newWindow, .offTheRecord), one of Chromium’s pages to onChromeTab, a file to the profile delegate’s profile(_:decideDestinationFor:).
  • Alloy-style pages (views) show CEF’s shorter menu (Back, Forward, Print, View Page Source, the editing commands, spelling suggestions) completed with Chrome’s link, image, audio and video items, Look Up and Emoji & Symbols, and, in windowed views, Speech and Writing Direction. CefKit runs these the same ways: View Page Source and the Open … items ask page(_:decideWindowOpenFor:), the Save … As items start a download, the Copy … items write to the general pasteboard.

Change the menu with contextMenu.customize. Each customization gets the menu the ones before it left, and what was clicked:

pageConfiguration.contextMenu.customize { menu, target in
    menu.remove(.viewSource, .print)
    if let link = target.linkURL {
        menu.insert(CefContextMenu.Item("Copy as Markdown") { page, _ in
            NSPasteboard.general.clearContents()
            NSPasteboard.general.setString("[\(page.title)](\(link.absoluteString))", forType: .string)
        }, after: .copyLinkAddress)
    }
    if !target.selectedText.isEmpty {
        menu.appendSection([
            CefContextMenu.Item("Search Notes") { _, target in search(target.selectedText) },
        ])
    }
}
  • A CefContextMenu is its items. An item has a title, isEnabled, isChecked, and is a command, a submenu or a separator (isSeparator). Chromium’s items carry their command, a CefContextMenuCommand; yours have an action, which gets the page and the target and may await. Make yours with CefContextMenu.Item(_:action:), CefContextMenu.Item(_:submenu:) and .separator.
  • contains(_:), menu[.saveLinkAs] (set it to change the item, nil to remove it), remove(_:), removeAll(where:), insert(_:after:), insert(_:before:) and handle(_:with:) find items in submenus too; appendSection(_:) adds items below a separator, and commands lists Chromium’s. Separators left at the ends or next to each other, and empty submenus, are dropped when the menu shows.
  • CefContextMenuCommand names Chromium’s commands (.openLinkInNewTab, .copyImage, .lookUp, .spellingSuggestion(0), .inspectElement, …) the same in Alloy and Chrome style. Its raw value is Chrome’s command ID; one CefKit does not name, as a later Chromium may add, keeps its value, and its item shows and runs.
  • A chosen Chromium item runs natively. To run your own code instead, keeping Chromium’s title, give the item an action:
pageConfiguration.contextMenu.customize { menu, _ in
    menu.handle(.openLinkInNewTab) { _, target in openTab(target.linkURL, inBackground: true) }
}
  • CefContextMenuTarget describes the click: location, linkURL, sourceURL and mediaType (image, video, audio, canvas…), mediaState, pageURL, frameURL (in a subframe), titleText, selectedText, isEditable, editing (what the field allows), misspelledWord and spellingSuggestions. A menu of your own acts on them with page.replaceMisspelling(with:) and page.learnSpelling(_:).
  • showsInspectElement adds Inspect where Chromium has none (Alloy style). isEnabled = false shows no menu.

To show the menu yourself, implement page(_:runContextMenu:for:): it gets the menu as it will show and returns the item the user chose, or nil for none; CefKit runs it. The value is all a custom NSMenu or SwiftUI menu needs. CefContextMenuPresenter is the stock menu:

final class MenuPolicy: CefPageDelegate {
    func page(_ page: CefPage, runContextMenu menu: CefContextMenu, for target: CefContextMenuTarget) async -> CefContextMenu.Item? {
        // No menu over the app's drawing canvas; the stock menu elsewhere.
        if target.mediaType == .canvas { return nil }
        return await CefContextMenuPresenter.present(menu, for: target, in: page)
    }
}

What Chrome has that CEF does not let an Alloy-style menu offer: Loop, Show Controls and Picture in Picture on media, Copy Video Frame, the canvas’s Save Image As and Copy Image, Search and Lens (Alloy has no search engine), Translate, Create QR Code, and Speech and Writing Direction in offscreen views. Use a Chrome-style page for those.

Was this page helpful?