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

Configuration, flags and features

Starting Chromium: presets, Chromium feature and switch overrides, preferences, languages, services, privacy and policies.

var configuration = CefRuntime.Configuration.chrome
configuration.disabledFeatures.formUnion(["WebUIOmniboxPopup"])
configuration.extraCommandLineSwitches = ["proxy-server": "socks5://localhost:1080"]
configuration.preferences["browser.confirm_to_quit"] = false

Starting Chromium

A SwiftUI app conforms to CefSwiftApp instead of App. Before SwiftUI starts, it installs the NSApplication subclass Chromium needs (CefApplication) and calls CefRuntime.shared.initialize(configuration:) with runtimeConfiguration:

@main
struct MyApp: CefSwiftApp {
    static var runtimeConfiguration: CefRuntime.Configuration {
        var configuration = CefRuntime.Configuration.embedded
        configuration.isOffscreenRenderingEnabled = true
        return configuration
    }

    init() {
        // Chromium is running here; register scheme handlers before any page loads.
    }

    var body: some Scene {
        WindowGroup { ContentView() }
    }
}

If Chromium cannot start, CefSwiftApp prints the reason and exits with status 1. If another instance of the app already uses the same data directory, Chromium hands the launch to it and this process exits with status 0; see Relaunching.

An AppKit app initializes the runtime first thing in main, before anything touches NSApp and before it starts work on other threads (loading the framework makes Chromium’s allocator the default malloc zone, and a thread freeing memory while the zones are swapped can crash the app):

@main
@MainActor
enum Main {
    static func main() {
        do {
            try CefRuntime.shared.initialize(configuration: .embedded)
        } catch .anotherInstanceRunning {
            exit(0)
        } catch {
            fatalError("\(error)")
        }
        let delegate = AppDelegate()
        NSApp.delegate = delegate
        withExtendedLifetime(delegate) { NSApp.run() }
    }
}

Quitting through NSApp.terminate(_:) closes every page first, so pages can run beforeunload handlers, and then shuts Chromium down; there is no shutdown call of your own to make. CefRuntime.shared.state goes from .notStarted through .starting to .running, and at quit through .stopping to .stopped. Chromium starts once per process: initialize throws CefError.alreadyInitialized while it runs and CefError.shutDown after it has stopped.

Configuration

Start from a preset and change what you need:

Preset Use
CefRuntime.Configuration.embedded Showing your own or trusted web content. Turns off background networking, component updates, Widevine, sync, translation, preloading, hyperlink auditing, password saving and autofill, first-run and default-browser prompts, and starts renderer processes only when a page needs one. With component updates off, CRLSets and the Certificate Transparency log list go stale, so an app that shows arbitrary sites should turn services.componentUpdates back on.
CefRuntime.Configuration.chrome Arbitrary sites with Chrome’s services. Keeps session cookies across launches and skips first-run and default-browser prompts; everything else is as Chromium has it and as users set it in chrome://settings, Widevine included.
CefRuntime.Configuration() Chromium’s defaults.

Common options:

Property Effect
isOffscreenRenderingEnabled Required for .offscreen pages. Off by default.
customSchemes URL schemes of your own, registered in every Chromium process. See Serving your own content.
preferences Chromium preferences by dotted name. See Preferences.
productName, stringOverrides Your product name, and replacements for other built-in strings. See Customizing Chromium’s own pages.
chromeToolbar Hides Chrome app-menu commands, toolbar buttons and page-action icons in Chrome-style windows.
extensions Extensions the app installs: .webStore(id), .package(at:id:version:), .unpacked(at:). See Extensions.
nativeMessagingHostDirectories Directories of native messaging hosts extensions may use, besides Chromium’s own; .chrome lists Google Chrome’s and Chromium’s. See Native messaging hosts.
processPolicy How many helper processes Chromium keeps running. See Footprint and launch time.
enabledFeatures, disabledFeatures Chromium feature names, passed as --enable-features and --disable-features. CADisplayLinkInGpu in enabledFeatures makes frames follow the display’s refresh exactly, as in Chrome, but windowed pages then show white bars while an animation grows them (measured).
safeStorage, keychainItem Whether Chromium uses the keychain, and which item. See Keychain access.
services, network, privacy, security, credentials Component updates, protected media, translation and system notifications; preloading and DNS over HTTPS; third-party cookies and hyperlink auditing; HTTPS-First; password saving and autofill. See Services and privacy.
enterprisePolicy Whether Chromium applies administrator-managed policies, and from which preferences domain. See Enterprise policies.
authenticationPrompt Who asks for HTTP sign-in credentials. See HTTP authentication.
services.protectedMedia Whether Chromium fetches Google’s Widevine CDM for protected (DRM) media: .automatic, .disabled (the .embedded preset), or .preinstalled(widevineDirectory:). See Playing streaming services.
services.systemMediaDecoders Experimental, empty by default: .audio plays AAC, AC-3, E-AC-3 and Apple Lossless with macOS’s decoders, .video H.264 and HEVC (re-encoded as VP9), in a sandboxed XPC service the systemMediaDecoders capability adds. See System media decoders.
rootCacheDirectory Where Chromium keeps its data: Local State, the default profile in Default, each persistent profile in Profile-<id> beside it. Defaults to ~/Library/Application Support/<bundle ID>/CefSwift. See Profiles.
persistsSessionCookies Whether session cookies survive a relaunch.
localization, acceptLanguages The language of Chromium’s own interface, and the languages pages are offered. See Languages.
userAgent How the page names itself to sites: Chromium’s own, with your product’s token, or a string of your own. See Compatibility with bot protection.
logSeverity, logFile Chromium’s log.
remoteDebuggingPort Exposes the DevTools Protocol on a localhost port. Leave it nil in shipping apps.
isSandboxEnabled Chromium’s macOS sandbox for the helper processes. On by default; see Sandbox.
extraCommandLineSwitches, onBeforeCommandLineProcessing Any other Chromium switch, such as ["proxy-server": "socks5://localhost:1080"].
frameworkDirectory, helperExecutableURL Override where the framework and helper are found. Rarely needed.

Languages

configuration.localization chooses the language of Chromium’s own interface: menus, dialogs, error pages, chrome:// pages and the strings Chromium gives pages, such as a date picker’s.

Policy Language
.application (default) The app’s: the localization macOS picks for the app from those it has (Bundle.main.preferredLocalizations), which follows the user’s language order and the per-app language in System Settings. An English-only app shows Chromium in English.
.system The first of the user’s preferred languages (Locale.preferredLanguages) that Chromium has strings for.
.fixed("de") That language.

CefKit resolves the policy before Chromium starts, against the locale packs the bundle contains (cef bundle keeps those of the app’s localizations; see Bundling): the first choice with a pack, else the app’s development language, else English (en-US). CefRuntime.shared.locale is the result, such as "fr", "pt-BR" or "en-US". Identifiers map onto Chromium’s locales as Chromium matches them: zh-Hans is zh-CN and zh-Hant is zh-TW; pt is pt-BR; Spanish for Latin America and the US is es-419; English outside the US is en-GB; iw, tl, in and no are he, fil, id and nb. Chromium reads the locale once; a change applies at the next launch.

Telling Chromium a locale itself (extraCommandLineSwitches["lang"]) bypasses that check. For a locale without a pack, Chromium starts with a locale name its strings do not match: it reports the requested locale and shows English text.

acceptLanguages lists the languages pages are offered, the Accept-Language header and navigator.languages, most preferred first. Empty, the default, takes the user’s preferred languages at start-up, whatever the interface language: a French user of an English-only app gets English menus and French pages. Chromium adds each language’s base (fr-CA brings fr) to the header. The list applies at every launch and wins over the languages a user picks in chrome://settings/languages. A profile can have a list of its own; set it before the profile’s first page:

let profile = CefProfile.persistent(id: "client")
profile.acceptLanguages = ["de-CH", "fr"]

Spelling follows the spelling language of macOS (Keyboard settings, Text Input), as in Chrome on macOS; spellcheck.dictionaries reports it and browser.enable_spellchecking turns checking off.

Services and privacy

Typed options for what Chromium does on its own. Each defaults to Chromium’s behavior, which users can change in chrome://settings where Chromium offers the setting; any other value is set again at every launch (for a profile’s, as Chromium loads the profile) and wins over what users chose there. A key in preferences wins over the typed option that sets the same preference.

What the whole app shares is in the runtime configuration; what each profile can choose for itself is in profiles, a CefProfile.Configuration every profile starts from, and which a profile overrides in its own configuration (Profile settings):

Option Values Chromium setting Scope
services.componentUpdates .automatic, .disabled --disable-component-update App, at start-up
network.secureDNS .automatic, .disabled, .secure(templates:) dns_over_https.mode, dns_over_https.templates App
privacy.hyperlinkAuditing .automatic, .disabled --no-pings App, at start-up
profiles.translation .automatic, .disabled translate.enabled Profile
profiles.network.preloading .automatic, .standard, .extended, .disabled net.network_prediction_options Profile
profiles.network.proxy .automatic, .system, .direct, .servers(_:bypassing:), .autoConfiguration(_:) proxy Profile
profiles.privacy.thirdPartyCookies .automatic, .block profile.cookie_controls_mode Profile
profiles.security.httpsFirst .automatic, .balanced, .strict https_first_balanced_mode_enabled, https_only_mode_enabled Profile
profiles.credentials.passwordSaving .automatic, .disabled credentials_enable_service, credentials_enable_autosignin Profile
profiles.credentials.autofill .automatic, .disabled autofill.profile_enabled, autofill.credit_card_enabled Profile
var configuration = CefRuntime.Configuration.chrome
configuration.profiles.privacy.thirdPartyCookies = .block
configuration.profiles.security.httpsFirst = .balanced
configuration.network.secureDNS = .secure(templates: ["https://dns.example/dns-query{?dns}"])
  • Component updates keep data files current: certificate revocation (CRLSet) and Certificate Transparency lists, Safe Browsing file-type and SSL error lists, origin trials, subresource filter rules, and the Widevine CDM. Turned off, Chromium registers none of them; it still fetches one component of its own, the on-device model manifest, which no switch stops (design notes). Protected media that needs Widevine keeps the updater on, since the CDM arrives through it; see Widevine in Chromium.
  • Preloading covers DNS prefetch, preconnect, prefetch and prerender. .disabled saves those requests; navigations can take longer.
  • .secure(templates:) sends every lookup to those DNS-over-HTTPS servers, which can bypass a network’s split DNS or VPN resolver.
  • Blocking third-party cookies can break sign-in, payment and comment widgets embedded from another site.
  • .strict HTTPS-First warns before every HTTP page, intranet and device pages included; .balanced warns only for sites that usually have HTTPS.
  • passwordSaving = .disabled stops Chromium from offering to save passwords and from signing in automatically; it still fills passwords the profile saved earlier.
  • Hyperlink auditing is the request an <a ping> link sends when it is followed. Pages can still send requests of their own.

Chromium 156 keeps the Privacy Sandbox ad APIs (Topics, Protected Audience, ad measurement) off: their preferences default to off and are cleared at start-up, and no setting turns them on, so there is no option for them.

Preferences

preferences sets Chromium preferences, the settings behind chrome://settings, by dotted name. Each applies to every profile when the profile is first used, or once at start-up to the few preferences Chromium keeps for the whole app:

configuration.preferences["credentials_enable_service"] = false   // per profile: no password manager
configuration.preferences["webkit.webprefs.default_font_size"] = 18
configuration.preferences["browser.confirm_to_quit"] = false      // application-wide

To read or change them later, use a profile’s preferences for per-profile settings (Profiles), and the runtime’s for application-wide ones:

let confirms = CefRuntime.shared.preferences.value(named: "browser.confirm_to_quit")?.boolValue
try CefRuntime.shared.preferences.setValue(false, named: "browser.confirm_to_quit")

value(named:) returns nil for an unknown name. setValue(_:named:) throws CefError.operationFailed for an unknown name or a value of the wrong type, and restores the default when passed nil. Values are CefJSON, which accepts Swift literals.

CefProfile.preferences and CefRuntime.shared.preferences also give preferences typed keys, observation and their state. A CefPreferences.Key names a preference with the Swift type of its value; the common ones are static members, and Key<Bool>("dotted.name") makes others:

let preferences = profile.preferences
try preferences.set(false, for: .savesPasswords)
let size = preferences[.defaultFontSize]                 // Int?
try preferences.set(["de", "en-US"], for: .acceptLanguages)
try preferences.reset(.acceptLanguages)                  // its default again

for await languages in preferences.observe(.acceptLanguages) {
    print(languages ?? [])                               // now, then on each change
}

canSet(_:) is false for a preference an enterprise policy manages or a command-line switch set; Chromium does not say which of the two. isDefault(_:) tells whether anything set a preference. Chromium has no call that reads a default while another value is set, so to see one, reset(_:) the preference. observe(_:) yields the value first, then each change, from Chromium’s settings pages as well as from your code, for as long as you iterate it.

Enterprise policies

Chromium applies the policies an administrator manages for Chrome (HomepageLocation, PasswordManagerEnabled, URLBlocklist, …) only from a preferences domain the app names:

configuration.enterprisePolicy = .applicationBundleIdentifier   // or .domain("com.google.Chrome")
enterprisePolicy Domain
.disabled (default) None: no policies apply.
.applicationBundleIdentifier The app’s bundle identifier, which an administrator manages as they would com.google.Chrome.
.domain(_:) Another domain, such as Chrome’s, to follow what is managed for Chrome.

Values a configuration profile forces (/Library/Managed Preferences) are mandatory policies: users cannot change them. Values in the user’s own preferences for the domain, such as defaults write <domain> ShowHomeButton -bool true, are recommended policies: they set the default, which users can change. On a Mac that is not managed, Chromium ignores the policies it counts as sensitive. chrome://policy, in a Chrome-style page, lists what applies. The app’s own UserDefaults are not policies unless the domain is the app’s and the names are Chromium’s.

Was this page helpful?