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

CefSwift

Build a Chromium browser, or embed Chromium, in a Mac app written in Swift and SwiftUI, on the official prebuilt CEF.

CefSwift embeds Chromium in macOS apps written in Swift, through the official prebuilt Chromium Embedded Framework (CEF). You get Chromium’s pages, tabs, profiles, extensions, bookmarks and history as Swift types, without a Chromium checkout or a fork to rebase.

import CefSwiftUI
import SwiftUI

@main
struct MyApp: CefSwiftApp {
    var body: some Scene {
        WindowGroup {
            CefWebView(url: URL(string: "https://example.com")!)
        }
    }
}

Bundle it with swift package cef bundle --product MyApp and open dist/MyApp.app (Install). Gallery: ObservableStateDemo.

Where to go next

Pre-1.0

CefSwift uses the official prebuilt CEF at the version CEF_VERSION.json pins; custom CEF builds are not supported. Its API can change between minor releases, so depend on one minor version (.upToNextMinor(from: "0.3.0")).

Task-oriented reference for CefSwift, a library that embeds CEF in any macOS app and exposes CEF’s and Chromium’s capabilities to Swift. The core, CefKit, covers the runtime, pages, profiles, views and windows; CefSwiftUI adds SwiftUI; CefPasskeys and CefChromium are optional libraries. What a browser product decides (its UI, defaults, when to use a capability) is the app’s: the Browser example in Examples/ shows one built this way.

Snippets assume import CefSwiftUI, which re-exports CefKit; an AppKit app imports CefKit alone (see In AppKit), and passkey and Chromium-store snippets also import CefPasskeys or import CefChromium. The runtime, page, window and profile APIs are @MainActor.

How CefSwift works inside, and why. For how to use it, see the guide.

CefSwift is a library for embedding CEF in a macOS app. The core, CefKit, wraps CEF’s C API and the Chromium behavior an embedder has to work with or around; the other modules and the examples build on it:

Where What Examples
CefKit (core) What any app embedding CEF needs and could not write itself: the runtime, pages, profiles, the AppKit host views, CEF Views windows (CefWindow), handlers and delegates, offscreen rendering and its accessibility, discarding CefRuntime, CefPage, CefProfile, CefOffscreenPageView, CefWindow
CefSwiftUI SwiftUI on top of CefKit, nothing else CefSwiftApp, CefWebView, setToolbar, setPageOverlay
CefPasskeys, CefChromium (optional) Capabilities on Chromium internals some apps want: passkeys the app answers; Chromium’s bookmark, history and suggestion stores, its extensions, its tabbed windows and tab strip, and its bubbles CefPasskeyController, CefBookmarks, CefExtensions, CefChromeWindow, CefTabs, CefChromiumSurface
CefBundling, cefswift, CefPlugin Build time: the app bundle, its helpers, signing and checks swift package cef bundle, Scripts/xcode-embed.sh
Examples Product decisions written against the public API: UI, defaults, heuristics for when to use a capability the Browser’s tab rail, toolbar, swipe indicator, Memory Saver, permission names

The rule: the library holds what an app cannot write against its public API, because it calls the CEF C API, hooks Chromium or works around a CEF or Chromium limit, plus the defaults an embedder cannot ship without: the built-in sheets and presenters that answer a delegate method nobody implemented, each replaceable. Everything else belongs to the app.

Modules

CefSwiftUI   CefSwiftApp, CefWebView (over CefKit's host views), SwiftUI modifiers,
    │        CefWindow.setToolbar, setTabAccessory and setPageOverlay
    │  CefPasskeys  optional: CefPasskeyController (a CefPageAttachment), passkey
    │     │         stores and the passkey sheet
    │     │  CefChromium  optional, bound to the pinned CEF: CefBookmarks, CefHistory,
    │     │     │         CefAutocomplete, CefExtensions, CefTabs, CefChromeWindow,
    │     │     │         CefTab and CefTabGroup (on CefKit's service hosts);
    │     │     │         CefChromiumSurface, chromiumSurfacePolicy and their SwiftUI
    │     │     │         glue (on Chromium's AppKit classes)
CefKit       CefRuntime, CefPage, CefWindow, CefPageDelegate, CefBridge,
    │        CefDevTools, CefProfile, CefPageAttachment, configuration and policy types; the AppKit
    │        host views CefWindowedPageView and CefOffscreenPageView
    │        (with its compositor and accessibility elements), the internal
    │        service hosts and tab discarding, no SwiftUI
CCef         vendored CEF C headers, the generated bridge, the runtime loader (C)

CefBase      reference counting, strings and process messages, shared by
             CefKit and the helper (no Foundation, no AppKit)
CefRenderer  renderer-side features (bridges, user scripts, evaluation) on
             the V8 API, run by the helper
CefHelper    the helper-process executable (product cefswift-helper)
CefHelperStartup  the helper's startup library (product cefswift_helper_startup),
             which seals the sandbox before the framework's code runs

CefBundling  the bundle: framework, helpers, Info.plists, entitlements,
             signing, cef doctor (Foundation only)
cefswift     the command-line tool over CefBundling (Sources/CefSwiftTool),
             run by the plugin and by the Xcode build phase
CefPlugin    swift package cef download | bundle | info | clean | doctor |
             package | notarize; builds the product, the helper and its
             startup library with SwiftPM and runs cefswift

Extension points

CefKit names no optional feature. An optional module, such as CefPasskeys or CefChromium, plugs into it at these points:

  • CefPageAttachment (public), through CefProfile.attachments (every page of a profile, Chromium’s own included) and CefPage.Configuration.attachments: told when Chromium has created a page (pageDidCreate(_:)), when a discarded one is created anew (pageDidRestore(_:)) and when it closes (pageDidClose(_:)). An attachment whose preparesBeforeFirstDocument is true holds the first page: the page starts on about:blank, CefPage.bootstrap() awaits every attachment with the task-local settingUp set (so their DevTools calls do not wait for ready()), and only then loads the page. Without such an attachment nothing is held: adopt(_:) completes ready() and then tells the attachments, in a task, so that one attachment cannot delay every page. Such a page’s native popups are opened in a page CefKit creates (openPopupInNewPage), since Chromium runs a native popup’s first document before anything can attach to it.
  • CefProfile.moduleState(_:make:) (package): one object per type that a module keeps for a profile, made on first use.
  • CefWindow.moduleState(_:make:) and existingModuleState(_:) (package): the same for a CefWindow. A state object that is a CefWindowParticipant is told when the window is destroyed (windowDidClose(_:)).
  • CefWindow.addChromeCommandInterceptor(_:) (package): decides Chrome commands in every CefWindow, from Chrome’s UI and from CefPage.execute(_:disposition:), after the page’s delegate and before Chromium runs them.
  • CefWindow.Configuration.moduleValues (package): values a module keeps in a window configuration, by type, dropped for the window’s popups; showsChromiumStatusBubble and showsChromiumZoomBubble (package) set the page’s chrome_status_bubble and chrome_zoom_bubble. CefChromium’s status bubble uses the public pageOverlay.
  • The internal service hosts (package): CefServiceHosts (CefProfile.serviceHosts), CefServiceHost and CefServiceHost.Module. A module declares its own hosts and modules and calls them (Internal-page services).

Inside CefKit, an object holding CEF references outside any page is a CefShutdownParticipant: it adds itself with CefRuntime.addShutdownParticipant(_:), held weakly, and is told to release them after the last page and window and before the profiles’ request contexts and cef_shutdown(). The service hosts (a module’s included) and the media router are participants.

A module also uses a few package members of CefKit that are not public API: CefDevTools.addListener(for:_:), removeListener(_:for:) and leaseCount(_:) (synchronous, ordered event listeners and domain leases), CefPage.decision(_:_:) with CefPage.DecisionScope (a question cancelled when its page or document goes), CefDialogPresenter.run(_:in:) (an alert that dismisses itself on cancellation), CefLog, CefWindow.owning(_:), CefProfile.storageDirectory (now public), and CefObjCHook for overrides of Chromium’s AppKit classes.

CefChromium wraps Chromium’s own browser features, which are bound to Chromium-private interfaces of the pinned CEF: its stores (profile.bookmarks, history and autocomplete, kept weakly in the profile’s module state) and the surfaces of Chrome-style windows (window.chromiumSurfacePolicy, kept in the window’s module state). It depends on CefKit and on CCef and CefBase for Chromium’s command and string identifiers. Its surface handling starts on the first use of its window API: that installs the AppKit overrides and the command interceptor once, for every window, and a window’s state, made on first use or when Chromium first attaches a child window to it, takes up the surfaces already attached. Until then Chromium’s interface shows natively, as without the module.

CefProtectedMedia is FairPlay Streaming in Chromium pages (guide), built only on CefKit’s public API: a CefBridge (cefswiftFairPlay, access limited to the listed origins), a CefUserScript for those origins’ top frames, and a CefPageAttachment that ends a page’s session when it closes.

page (listed origin, main frame)  fairplay.js: EME for com.apple.fps, catches the playlist and certificate
  │  bridge: open / license / control / close        frame and origin established by the browser process
app (CefFairPlay)                 checks origin, frame, sizes; CefFairPlayPlaylist: https segments, skd/https keys
  │  NSXPCConnection, both ways
<App> FairPlay.xpc                AVPlayer + AVContentKeySession; playlist served by a resource loader
  │  keyRequest (SPC) ──▶ page's license server ──▶ license (CKC)      state ──▶ element mirrors it

The service is an XPC service of its own (Sources/CefFairPlayService, product cefswift-fairplay) in the App Sandbox with outgoing connections only, separate from the media decoders’ service, which has no network. One service process holds every page’s session (at most eight); the app names a session by the page and the page’s own session name.

Was this page helpful?