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

Profiles and private windows

Default, persistent and incognito profiles: what each keeps, how they load, and private windows.

import CefChromium

let work = CefProfile.persistent(id: "work", displayName: "Work")
_ = try await CefChromeWindow.open(url: url, profile: work)
_ = try await CefChromeWindow.open(url: url, profile: .incognito())   // a private window

Google sign-in works in a profile like any site’s (verified by hand). Gallery: ProfilesDemo. Browser example: Features/PrivateTabs opens private windows on the incognito profile.

A CefProfile holds cookies, storage, cache, preferences, extensions and theme. Pages that share a profile share all of it.

Profile Storage
CefProfile.default <root>/Default, Chromium’s own profile, loaded as Chromium starts; used when CefPage.Configuration.profile is nil.
CefProfile.persistent(id:displayName:) <root>/Profile-<id>, with characters other than lowercase letters, digits, - and _ percent-encoded. The same identifier returns the same profile.
CefProfile.incognito() In memory only; discarded with the profile. Its isIncognito is true.

<root> is CefRuntime.Configuration.rootCacheDirectory, by default ~/Library/Application Support/<bundle ID>/CefSwift. profile.storageDirectory is where a loaded profile keeps its files, as its request context reports it (get_cache_path); nil for an incognito profile.

let profile = CefProfile.persistent(id: "work", displayName: "Work")
try await profile.ready()                        // loaded by Chromium, from its directory
try profile.preferences.set(false, for: .savesPasswords)
let fontSize = profile.preferences[.defaultFontSize]
profile.setColorScheme(.dark, accentColor: .systemIndigo)

let cookies = try await profile.cookies(for: url)   // [CefProfile.Cookie]
try await profile.setCookie(CefProfile.Cookie(name: "theme", value: "dark", domain: "example.com", sameSite: .lax))
try await profile.deleteCookies(for: url, named: "session")

A profile’s id is its identity and names its storage in both engines; displayName is what to show, and can change without moving anything. Store id to find the profile again. Identifiers map to directory names one to one, also on a case-insensitive volume, so "a/b", "a_b", "Work" and "work" are four profiles, and no name is one Chromium uses in <root> itself (Default, Local State, Profile 1). CefChromium’s bookmarks, history and autocomplete hold their profile, so CefProfile.incognito().autocomplete keeps its profile alive while you use it; the profile does not hold them back, so neither keeps the other alive forever.

A CefProfile.Cookie carries everything CEF stores: name, value, domain (a leading dot for a domain cookie), path, isSecure, isHTTPOnly, expirationDate (nil for a session cookie), sameSite, priority, and Chromium’s creationDate and lastAccessDate. CEF 158 reports no partition key, so a partitioned (CHIPS) cookie is listed without the site it is keyed to. Every cookie call returns once Chromium has finished:

Call Returns
cookies(for:) The cookies a request to the URL carries, HTTP-only included; all of them with nil.
enumerateCookies(for:using:) Hands them over one at a time, on the main actor, until the closure sets stop.
setCookie(_:for:) Nothing; throws CefError.operationFailed when Chromium refuses the cookie (a domain that does not match the URL, characters a cookie cannot hold, SameSite=None without isSecure). Without a URL, the cookie’s domain and path make one.
deleteCookies(for:named:) How many Chromium deleted: the named one, every host cookie of the URL, or with both nil every cookie.
deleteCookies(for:where:) How many the predicate picked.
flushCookies() Nothing, once the store is on disk.

A cancelled task stops waiting at once and throws CancellationError; Chromium finishes what it had started, and its answer is dropped. The same holds for the network maintenance calls below, resolveHost(_:), printToPDF(at:configuration:), cast(_:to:) (a route Chromium creates after the caller stopped waiting is ended) and CefRuntime.shared.installWidevine().

preferences.allValues(includingDefaults:) returns every preference as one JSON object. setColorScheme(_:accentColor:) themes Chrome-style UI and sets the prefers-color-scheme pages see.

Clearing a site’s data

clearSiteData(for:types:) deletes what one site keeps in the profile: its cookies, localStorage, IndexedDB, Cache Storage, service workers, file systems, Shared Storage and Storage Buckets, or the CefProfile.SiteDataTypes asked for. Other sites keep theirs, and the HTTP cache, which Chromium does not keep per site, stays.

// "Forget this site"
try await profile.clearSiteData(for: URL(string: "https://example.com")!)
// Sign out of it, keeping its offline data
try await profile.clearSiteData(for: URL(string: "https://example.com")!, types: [.cookies, .localStorage])

Only the address’s scheme, host and port count. CEF has no call for this, so it runs the DevTools Protocol’s Storage.clearDataForOrigin in one of the profile’s live pages, whose devTools session attaches with no domain enabled (see Features that use the DevTools Protocol); a discarded page is not restored for it, and a profile with no live page throws. Cookies are deleted for the origin’s host: a cookie a parent domain set (Domain=example.com, seen from www.example.com) stays, as with deleteCookies(for:named:). Clearing one site’s cookie, localStorage, IndexedDB database and Cache Storage cache took 28 ms (CEF 158.0.6, M2, 2026-11-28).

Zoom levels, search engines, browsing data and passwords

For a browser’s own settings screens, CefChromium also reaches what Chromium’s settings pages change:

import CefChromium

let profile = CefProfile.default

// Sites with a zoom level of their own (chrome://settings/content/zoomLevels)
for site in try await profile.zoomLevels.sites() { print(site.host, site.percent) }
try await profile.zoomLevels.remove(host: "example.com")

// Search engines and the default (chrome://settings/searchEngines)
let engines = try await profile.searchEngines.engines()
let current = try await profile.searchEngines.defaultEngine()

// "Delete browsing data", no page needed
try await profile.browsingData.clear([.cookiesAndSiteData, .cache], in: .lastHour)

// The password manager (chrome://password-manager)
let saved = try await profile.passwords.list()
try await profile.passwords.add(url: URL(string: "https://example.com")!, username: "me", password: "…")

// Cameras and microphones, for a device picker (chrome://settings/content/camera)
let cameras = try await profile.captureDevices.list(.camera)
if let camera = cameras.devices.first { try await profile.captureDevices.setPreferred(camera, for: .camera) }

// Sites that handle a scheme (chrome://settings/handlers)
for handler in try await profile.protocolHandlers.list().handlers { print(handler.scheme, handler.host) }

// Autofill: addresses read and written, payment cards read without their numbers
try await profile.autofill.save(CefAutofill.Address(fields: [.fullName: "Ada Lovelace", .email: "[email protected]"]))
let addresses = try await profile.autofill.addresses()
let cards = try await profile.autofill.paymentCards()   // "Visa ••••1111"

// Fonts and languages Chromium offers; the choices are preferences
let fonts = try await profile.chromiumSettings.fonts()
let languages = try await profile.chromiumSettings.languages()
try profile.preferences.set("Helvetica", for: .sansSerifFontFamily)

// Every Chromium tab's lifecycle (chrome://discards)
for tab in try await CefTabLifecycle.tabs() { print(tab.title, tab.state, tab.discardCount) }
API Chromium’s service Host
zoomLevels The zoom-levels messages of chrome://settings’ site-settings handler (fetchZoomLevels, removeZoomLevel) chrome://settings
searchEngines Its search-engines handler (getCategorizedTemplateUrls), read only chrome://settings
browsingData Its clear-browsing-data handler (clearBrowsingData), Chromium’s BrowsingDataRemover chrome://settings
passwords chrome.passwordsPrivate chrome://password-manager
captureDevices Its media-devices handler (initializeCaptureDevices, setPreferredCaptureDevice) chrome://settings
protocolHandlers Its protocol-handlers handler (observeProtocolHandlers, setDefault, removeHandler, setHandlersEnabled) chrome://settings
autofill chrome.autofillPrivate chrome://settings
chromiumSettings Its font handler (fetchFontsData) and chrome.languageSettingsPrivate chrome://settings
CefTabLifecycle discards.mojom.DetailsProvider chrome://discards

These are WebUI message handlers rather than Mojo interfaces: the service host defines cr.webUIResponse and cr.webUIListenerCallback, which the handlers call back. Several of them stop the browser process with a CHECK when given a value they do not know (an unknown content-setting type, a deletion preference), so CefChromium sends only values built from its own enums or read back from Chromium.

Some calls work only from a page in a window that shows, and are left out:

Left out From a hidden service host (CEF 158.0.6)
Choosing the default search engine (setDefaultSearchEngine) Ended the browser process (a CHECK)
Clearing history and the download list through clearBrowsingData Ended the browser process; profile.history.remove(_:) removes history
The 15-minute time range (Chromium’s iOS one) Ended the browser process
A password itself (requestPlaintextPassword) Asks the user to authenticate with macOS, and never answered in 120 s
Clearing one site group (clearSiteGroupDataAndCookies) Ended the browser process given an origin instead of Chromium’s grouping key
Site permissions through the site-settings handler Ended the browser process for an unknown type name; profile.siteSettings covers them through CEF
Payment cards’ numbers, and saving or removing a card Left out by design: paymentCards() copies only the label, name, network and expiry out of the host

All of them work from chrome://settings or chrome://password-manager shown in a Chrome-style window, where the user makes the choice.

None is available in an incognito profile, whose settings Chromium shows in its original profile; the methods throw. A zoom level is saved by zooming a page on the site (CefPage.zoomLevel); the handler can only list and remove them. Removing one returns the site’s open pages to the default zoom, and CefKit reads their zoomLevel back. changes on zoomLevels, searchEngines, passwords, captureDevices, protocolHandlers and autofill reports changes while their host runs. Chromium saves no address while fillsAddresses is off. The preferred camera and microphone are the ones Chromium picks when a page asks for none by deviceId; listing them asks macOS for nothing. CefTabLifecycle lists Chrome-style pages and CefChromeWindow tabs, of every profile; Alloy-style pages have no Chromium tab. Warm-call latencies are in Settings services, measured. Alloy-style pages (CefWebView) do not use the password manager; Chrome-style pages fill and save with it.

Measured with an AppKit probe on CEF 158.0.6 (M2, macOS 27.2.1, AC power, other builds running, 2026-11-29): the settings host’s first call took 1.1 to 2.1 s, starting the host; then warm calls, p50 / p95 of 20:

Call p50 p95
zoomLevels.sites() 0.5–0.9 ms 1.4–2.4 ms
searchEngines.engines() (5 engines) 0.9–1.6 ms 5–15 ms
passwords.list() 0.7–0.8 ms 1.7–250 ms
browsingData.clear([.cookiesAndSiteData, .cache], in: .lastHour) 7–10 ms (one run each)
passwords.add(…) 3.6 ms (one run)

What is configured where

A profile holds the defaults for every page in it: pages the app creates and pages Chromium creates itself (native popups, tabs and windows opened from Chrome’s UI, extension pages). A page adds to them or overrides them where CEF lets it. The runtime keeps what is process-wide, and what every profile starts from.

Concern Runtime (CefRuntime, its Configuration) Profile (CefProfile) Page (CefPage.Configuration, its delegate)
Scheme handlers registerSchemeHandler(scheme:domain:handler:): every profile, present and future registerSchemeHandler(scheme:domain:handler:): this profile, in place of the runtime’s —
Request filter — requestFilter: its pages’ requests and their workers’ requestFilter: the page’s own requests, instead of the profile’s
Permissions — delegate’s profile(_:decidePermissionFor:in:); siteSettings answer first delegate’s page(_:decidePermissionFor:), instead of the profile’s
Downloads — downloadPolicy, delegate’s profile(_:decideDestinationFor:), downloads downloads (the page’s share of the profile’s)
User scripts — userScripts userScripts, after the profile’s; addUserScript(_:), removeUserScript(_:)
Bridges — bridges bridges; one of the same name replaces the profile’s
Attachments — attachments attachments, after the profile’s
Chromium settings profiles: what every profile starts from; network.secureDNS, privacy.hyperlinkAuditing, services, switches and features: process-wide configuration: third-party cookies, HTTPS-First, passwords, autofill, translation, preloading, proxy content: JavaScript, images, WebGL, storage, clipboard, fonts, encoding
Preferences by name preferences (every profile, and the app’s own) preferences —

Precedence is page, then profile, then runtime, and nothing is set in two places with different meanings. A page’s popups, and the tabs Chromium opens inside a CefKit window, take the configuration of the page that opened them; a page in a window Chromium opens by itself has the default configuration, so the profile’s policy is all it gets. CefKit’s hidden service pages get none of a profile’s page policy.

Profile settings

profile.configuration holds the Chromium settings a profile applies to itself. It starts as CefRuntime.Configuration.profiles, and changing any of it overrides it for that profile alone, at once or as Chromium loads the profile; setting an option back to .automatic resets its preference. An incognito profile that blocks third-party cookies and saves no passwords, and one that goes through a proxy:

let incognito = CefProfile.incognito()
incognito.configuration.privacy.thirdPartyCookies = .block
incognito.configuration.credentials.passwordSaving = .disabled

let work = CefProfile.persistent(id: "work")
work.configuration.network.proxy = .servers("proxy.example:8080", bypassing: ["*.internal", "<local>"])
// .automatic, .system, .direct, .servers(_:bypassing:), .autoConfiguration(URL)

The proxy is the profile’s proxy preference, which Chromium applies to its request context as it changes. A --proxy-server switch on the command line wins over it for the whole app.

Loading a persistent profile

Chromium loads a persistent profile in the background the first time anything uses it in a launch, and creates its directory the first time ever; the default and incognito profiles are ready at once. What waits, and what does not:

Called while the profile loads What happens
Pages, in every host (CefWebView, the AppKit views, CefWindow, openChromeWindow) and their popups Wait, and are created once it is loaded. The page stays .pending, and load(_:), ready() and waitUntilLoaded(timeout:) work as for any page being created. A CefWindow opens at once and gets its page when the page comes. A view given another browser, or none, meanwhile does not get this one later. Quitting closes the pages still waiting: their ready() throws CefError.pageClosed, and the profile’s ready() throws CefError.shutDown.
cookies(for:), enumerateCookies(for:using:), setCookie(_:for:), the deleteCookies calls, flushCookies() Chromium queues them until the profile is loaded.
data(for:), bytes(for:), download(for:to:), resolveHost(_:), the clear… calls Wait for the profile.
siteSettings.set(…), setDefaultSetting(_:for:), setColorScheme(_:accentColor:) Apply once it is loaded.
preferences, and siteSettings reads Have nothing yet: reads return nil or .default, and preferences.set throws. Await profile.ready() first.

If Chromium cannot load the profile from its directory, nothing falls back to memory: its pages close as they are created, ready() (the profile’s and each page’s) throws CefError.profileUnavailable(reason), its requests throw the same, and CefKit logs the reason. Something in the way of the directory, a file of the same name, is one cause.

The rule behind the layout, from CEF’s cef_types.h and as Chromium 156 applies it: root_cache_path is Chromium’s user data directory, and a request context’s cache_path must be a direct child of it. Chromium’s profile manager creates profiles nowhere else; for any other path, a nested one such as <root>/Profiles/<id> included, it logs “Cannot create profile at path” and gives the context a new in-memory profile, and CEF still reports the context initialized. Chromium compares the paths with symbolic links resolved, so a profile path through a link (/var for /private/var, where FileManager.temporaryDirectory points) is refused too; CefKit resolves the root before it builds profile paths. The global cache_path is always the root itself: Chromium ignores a child there and uses Default.

Earlier CefSwift builds put persistent profiles at <root>/Profiles/<id>. Chromium refused that path, so those profiles were in memory and nothing of theirs was saved: what is left there is empty directories, which you can delete. Nothing is migrated.

CefKit has no call that deletes a profile’s data from disk. Chromium keeps a profile it has loaded open until it shuts down, so remove a profile’s directory only while the app is not running, for instance early at the next launch, before CefRuntime.initialize.

Profile policy

A profile holds the defaults for every page in it, and CEF scopes what it can per request context, so CefKit scopes it there too:

  • Requests. Every request context a profile has, its own and the shared one of the default profile, carries a cef_request_context_handler_t (CefProfileContextHandler) whose get_resource_request_handler applies the profile’s requestFilter. CEF asks it only when the page’s client returns no handler for the request, which a page’s client does unless the page has a filter of its own (CefRequestFiltering.page) or is one of CefKit’s service pages (.unfiltered, a handler that only checks external protocols). Requests without a page, a service worker’s or a shared worker’s, reach only a context handler: CEF picks one of the handlers of the contexts that share the storage, which for a profile are all the same. A context Chromium creates itself, for a window it opens from its own UI, gets one from get_default_request_context_handler, which finds its profile from on_request_context_initialized. CEF does not hand the app’s own cef_urlrequest_ts to these handlers.
  • Matching. A CefRequestFilter’s hosts, patterns and resource types are compiled into a C matcher (ccef_request_match). Each request is tested on its cef_resource_type_t first, then on its UTF-16 address as CEF hands it over, in get_resource_request_handler; a request the filter does not want gets no handler, so it never reaches Swift values or the filter. A request it wants gets a handler of its own whose on_before_resource_load builds the CefResourceRequest (the initiator comes from get_resource_request_handler), runs the filter, and whose get_cookie_access_filter applies .restrictCookies(to:). After .rewriteResponse(_:), its get_resource_response_filter builds an HTTPURLResponse from the read-only cef_response_t and asks the rewriter’s prepare; a rewrite gets a cef_response_filter_t (ResponseBodyRewrite) that reads every chunk into one buffer, rewrites it when CEF calls with no input (the body has ended), and writes the result out across as many calls as CEF’s output buffer needs. Past maximumLength it writes out what it held and copies the rest through.
  • Scheme handlers. register_scheme_handler_factory registers on the page context, so every context of a profile shares a registration. A runtime registration goes to the global context (cef_register_scheme_handler_factory) and to every other profile’s context as it is made; a profile’s own goes to its context and wins there. Removing one registers a NULL factory, or the runtime’s again.
  • Pages. A page’s effective user scripts, bridges and attachments are its profile’s followed by its configuration’s (a page bridge replaces a profile bridge of the same name). Permission and download decisions go to the page’s delegate, whose default implementation asks the profile’s CefProfileDelegate. A popup takes its opener’s configuration; a tab Chromium opens inside a CefKit window takes that window’s first page’s, since CEF gives it that page’s client, settings and extra_info; one in a window Chromium opens itself has the default client and no extra_info, so only its profile’s policy applies.
  • Settings. CefProfile.Configuration maps onto the profile’s preferences; a profile applies CefRuntime.Configuration.profiles, or its own, as it loads and again when it changes, resetting what an earlier value set. The proxy is the context’s proxy preference.

The request filter’s cost was measured with -benchmark filters: see design notes.

Profiles and their request contexts

CefProfile.default is Chromium’s Default profile under root_cache_path, loaded as Chromium starts. Its pages use a context that shares the global context’s storage (cef_create_context_shared), because the global context has no handler and the profile’s needs one (see Profile policy). Every other profile creates its own context on first use with cef_request_context_create_context: an empty cache_path for an incognito profile, <root>/Profile-<id> for a persistent one, the root taken with its symbolic links resolved (realpath), because Chromium’s profile manager makes a profile only in a direct child of its user data directory, compared that way. Anything else gets an in-memory profile, which CEF reports as an initialized context like any other.

A context created that way reports on_request_context_initialized once Chromium has loaded the profile, asynchronously for a disk profile (an incognito context is usable as soon as create_context returns, so CefKit counts it ready then). CefProfile.readiness follows it, .pending, .loading, then .ready or .failed(reason): the callback checks that the context’s get_cache_path is the directory asked for and that the directory now exists, which is how Chromium’s silent fall-back to memory is caught. A failed profile drops its context, and every call on it fails or does nothing.

Page creation goes through CefPage.profileAllowsCreation(for:_:) first, in every path: windowed, offscreen, Chrome’s own window and CefWindow’s browser view. cef_browser_host_create_browser_sync and cef_browser_view_create fail on a context that is not initialized yet, and the asynchronous cef_browser_host_create_browser would go ahead on the in-memory fallback, so a page on a profile still loading stays .pending and the creation runs again once the profile reports; the last host asked for wins. The deferred creation is a token, creationAwaitingProfile, checked when the profile reports: a host view given another browser or none (stopHosting(in:)) or leaving its window, a close, or a quit clears it, and nothing is created. Such pages are in no page list, so CefRuntime tracks them (pagesAwaitingProfiles) and quitting closes them first, which ends their ready() with CefError.pageClosed. A CefWindow creates its window at once and adds the browser view when the profile is ready. Popups need nothing: they share their opener’s context, which is loaded. The default profile and loaded profiles take the direct path, with no wait. A page on a failed profile closes as it would on a failed creation, and its ready() throws CefError.profileUnavailable.

Persistent profiles: directly in the root, and loaded before use

Observed on 2026-11-14 with CEF 156.0.28 (Chrome runtime) on an M3, macOS 27.2, with Chromium’s log at info and each case run on a new root cache directory, then again on the same one.

The rule. cef_types.h says a request context’s cache_path must be “equal to or a child directory of” root_cache_path. Chromium 156 is stricter: its profile manager creates profiles only in a direct child of the user data directory (root_cache_path). With the earlier layout, <root>/Profiles/<id>, every persistent profile logged

ERROR:cef/libcef/browser/chrome/chrome_browser_context.cc:116] Cannot create profile at path …/Profiles/<id>

and got a new off-the-record profile instead, in windowed, offscreen and Chrome-style pages alike, at the first launch and every later one: the directory CefKit had made stayed empty, cookies, local storage and history lasted as long as the process, and CEF still reported the context initialized, so nothing in CefKit or SelfTest noticed. Moved to <root>/Profile-<id>, the same profiles were real: Chromium created the directory and wrote Cookies, Local Storage, History, Preferences and the rest, and found them at the next launch.

Links count. The comparison is made with symbolic links resolved: a root under FileManager.temporaryDirectory (/var/folders/…, a link to /private/var/folders/…) refused every <root>/Profile-<id> built from it, with the same silent fall-back. CefKit builds profile paths from realpath of the root. (URL.resolvingSymlinksInPath() does not help: it keeps /var.)

The global context. A cache_path other than the root itself is ignored for the global context: with <root>/Custom the directory was created and stayed empty, and the default profile lived in <root>/Default. CefKit therefore no longer has a cacheDirectory option; the default profile is always <root>/Default.

Creation while loading. Chromium creates a disk profile asynchronously; on_request_context_initialized reports it, 0.1–0.3 s after cef_request_context_create_context the first time, less once its directory exists. Until then cef_browser_host_create_browser_sync (windowed pages) fails, cef_browser_view_create gives a view whose page never appears (a CefWindow stayed empty, its page .pending), and preferences read nil and refuse writes; the asynchronous cef_browser_host_create_browser (offscreen, Chrome’s own window) waits by itself. An in-memory profile, incognito or a fall-back, is ready at once. CefKit waits for the callback before creating any page on a new profile, then checks the context’s get_cache_path and the directory, so a fall-back becomes CefError.profileUnavailable. SelfTest’s profileStorage group creates pages on brand-new profiles in each host, and runs two launches on one root to check what survives.

Was this page helpful?