Popups and permission UI
Answer permission requests, dialogs, sign-in and certificate questions with your own UI; handle new windows and popups.
final class Policy: CefPageDelegate {
func page(_ page: CefPage, decidePermissionFor request: CefPermissionRequest) async -> CefPermissionDecision {
await askUser(about: request.kinds, from: request.origin.absoluteString) ? .allow : .deny
}
}
Gallery: PermissionsDemo, ContextMenuDemo.
Browser example: Features/PageInfo asks for camera, location and the like and shows site permissions.
CefPageDelegate covers what observation cannot: decisions and one-time
events. Every method has a default, so implement only the ones you need.
Decisions Chromium can wait for are async: present your own UI, await the
user, and return.
final class Policy: CefPageDelegate {
func page(_ page: CefPage, decidePermissionFor request: CefPermissionRequest) async -> CefPermissionDecision {
await askUser(about: request.kinds, from: request.origin.absoluteString) ? .allow : .deny
}
func page(_ page: CefPage, runJavaScriptDialog dialog: CefJavaScriptDialog) async -> CefJavaScriptDialogResponse {
// Keep the native sheet for everything but alerts.
dialog.kind == .alert ? .accept() : await CefDialogPresenter.present(dialog, in: page.hostWindow)
}
}
| Method | Default |
|---|---|
page(_:runJavaScriptDialog:) async |
Native sheet |
page(_:confirmLeavingPage:) async (beforeunload) |
Native sheet |
page(_:decidePermissionFor:) async |
Hands the request to the profile’s delegate (CefProfileDelegate), which denies by default. Asked only when the site settings leave the request to the user; see Permissions |
page(_:credentialFor:) async (HTTP and proxy authentication) |
Native sign-in sheet; see HTTP authentication |
page(_:shouldProceedDespite:) async (certificate errors) |
false: the load is cancelled |
page(_:selectClientCertificateFor:) async |
Native sheet; asked only with CefPage.Configuration.clientCertificates = .delegate, otherwise Chromium’s picker. See Client certificates |
pageIsUnresponsive(_:) async |
Native sheet; Chrome-style pages show Chromium’s dialog instead. See Unresponsive pages |
page(_:decidePolicyFor:) (main frame and subframes) |
.allow |
page(_:decideWindowOpenFor:) |
CefWindowOpenDecision.default(for:) |
page(_:decideExternalProtocolFor:) async |
Native sheet (CefExternalProtocolPresenter); .deny when no app handles the scheme. See Links to other apps |
page(_:handleKeyEvent:isBeforePage:) |
false |
page(_:runContextMenu:for:) async |
Native menu at the click (CefContextMenuPresenter); see Context menu |
page(_:handleChromeCommand:disposition:) |
false: Chrome runs the command |
An async decision that stops mattering before you answer is cancelled:
a dialog, permission or certificate decision when the page
navigates away, and every decision when the page closes. The task
running your method is cancelled and its answer is ignored; the default
sheets dismiss themselves.
Events: pageDidCreate(_:), pageDidClose(_:), page(_:didOpen:)
(a popup or DevTools page opened on this page’s behalf, which inherits
the delegate), page(_:didFinishLoadWithStatus:),
page(_:didFailLoad:), page(_:didLog:) and
page(_:renderProcessDidTerminate:). Downloads have no event: each
CefDownload is observable, and the profile and page list them
(Downloads).
CefDialogPresenter provides the native sheets behind the defaults, so your
delegate can keep them for some cases.
Permissions
A permission request goes to the page’s delegate, whose default hands it
to the page’s profile: CefProfileDelegate.profile(_:decidePermissionFor:in:),
which denies unless the app sets a profile delegate. A profile delegate
decides for every page of the profile, pages Chromium opens itself
included, and a page’s own delegate decides for that page instead:
final class ProfilePolicy: CefProfileDelegate {
func profile(_ profile: CefProfile, decidePermissionFor request: CefPermissionRequest,
in page: CefPage) async -> CefPermissionDecision {
guard request.isMainFrame else { return .deny }
return await askUser(about: request.kinds, from: request.origin.absoluteString) ? .alwaysAllow : .deny
}
}
let profilePolicy = ProfilePolicy()
CefProfile.default.delegate = profilePolicy // held weakly, as a page's delegate is
A CefPermissionRequest has the kinds asked for, the asking origin
and the page’s topLevelOrigin, both URLs as CefSiteSettings takes them,
isMainFrame, and the asking frame where CEF names it (camera,
microphone and screen capture; for the other kinds CEF reports only the
origin). Chromium asks only when the profile’s site settings
leave a request to the user: the settings are the “check” side, what
Chromium consults without asking anyone, and .alwaysAllow or
.alwaysDeny stores the answer there.
Site settings
profile.siteSettings holds what each site may use, as Chrome’s site
settings do: a CefSitePermission (.camera, .microphone,
.geolocation, .notifications, .popups, .javaScript, .images,
.cookies, .sound, .automaticDownloads, .clipboard, .usbDevices,
.serialPorts, .hidDevices, .bluetoothDevices, …) set to .allow,
.block or .ask for an origin:
let site = URL(string: "https://meet.example")!
let settings = profile.siteSettings
settings.set(.allow, for: .camera, origin: site)
settings.setting(for: .notifications, origin: site) // .ask: the default applies
settings.setDefaultSetting(.block, for: .popups) // for every site without its own
settings.reset(origin: site) // the defaults apply again
for await change in settings.changes {
print(change.permission, change.origin)
}
setting(for:origin:) returns the value that applies: the site’s own or
the profile’s default. supportedSettings lists the values a permission
takes; Chromium has no .ask for content switches such as images and
JavaScript, and no .allow for device choosers, which ask for each
device. Cookies also take .sessionOnly. Settings belong to origins, so
every page of a site shares them.
changes reports every change for as long as you iterate it, including
those Chromium’s own prompts and chrome://settings make.
exceptions(for:) lists the values sites have of their own. Chromium has
no call for that; it reads the profile’s
profile.content_settings.exceptions preference, where Chromium keeps
them, so for an incognito profile, which keeps them in memory, it lists
none.
The settings are the “check” side of permissions: what Chromium consults
without asking anyone. The settings and the permission delegates
(Permissions) agree. Chromium does not ask
about a prompt-based permission (notifications, location, MIDI, window
management, …) that a site has .allow or .block for, and keeps the
answer the delegate gives, .allow or .deny, for the site as Chrome
does. Camera and microphone requests reach the delegate before Chromium
reads the settings, so CefSwift answers them from the settings itself, and
asks the delegate only about kinds that are still .ask. An answer there
applies to that request; .alwaysAllow and .alwaysDeny also store it.
Screen and system-audio capture (.screenCapture, .systemAudioCapture)
are kinds of their own, never answered by the camera’s or microphone’s
settings and never stored: granting one hands the page the screen without
Chromium’s picker, so the delegate is asked on every request. Camera
movement (.cameraPanTiltZoom) is separate from .camera too, stored as
CefSitePermission.cameraPanTiltZoom:
func page(_ page: CefPage, decidePermissionFor request: CefPermissionRequest) async -> CefPermissionDecision {
let (allowed, remember) = await askUserRemembering(about: request.kinds, from: request.origin.absoluteString)
switch (allowed, remember) {
case (true, true): return .alwaysAllow
case (true, false): return .allow
case (false, true): return .alwaysDeny
case (false, false): return .deny
}
}
Built-in sheets
Every sheet CefSwift shows by default answers a delegate method, so an app replaces any of them by implementing that method, and keeps the stock one for some cases by calling its presenter:
| Sheet | Delegate method | Presenter |
|---|---|---|
alert, confirm, prompt |
page(_:runJavaScriptDialog:) |
CefDialogPresenter.present(_:in:) |
Leaving a page (beforeunload) |
page(_:confirmLeavingPage:) |
CefDialogPresenter.confirmLeaving(isReload:in:) |
| HTTP sign-in | page(_:credentialFor:) |
CefDialogPresenter.requestCredential(for:in:) |
| Client certificate | page(_:selectClientCertificateFor:) |
CefClientCertificatePresenter |
| Unresponsive page | pageIsUnresponsive(_:) |
CefUnresponsivePagePresenter |
| File chooser | page(_:runFileDialog:) |
CefFileDialogPresenter |
| Download save panel | CefProfileDelegate.profile(_:decideDestinationFor:) |
CefDownloadPresenter |
Opening another app (mailto:, zoommtg:) |
page(_:decideExternalProtocolFor:) |
CefExternalProtocolPresenter |
| Page tooltip (not a sheet) | page.tooltipPolicy = .custom, then show page.tooltip |
The offscreen view’s toolTip; Chromium’s own elsewhere. See Tooltips |
| Context menu | page(_:runContextMenu:for:) |
CefContextMenuPresenter |
| Passkeys | CefPasskeyDelegate.page(_:decidePasskeyFor:) |
CefPasskeyPresenter |
The context menu’s Inspect item is a configuration
(contextMenu.showsInspectElement), and the offscreen view’s accessibility
label (“Web content”) gives way to one set with setAccessibilityLabel(_:).
Their text comes from three places:
- CefSwift’s resource bundles: the titles, messages and buttons of the
sheets above, CefKit’s in
CefSwift_CefKit.bundleand CefPasskeys’ inCefSwift_CefPasskeys.bundle, fromSources/<Target>/Resources/<language>.lproj/Localizable.strings. CefSwift ships English. Foundation picks their language as for every bundle an app loads: the app’s own, the localization macOS chose for the app, when the bundle has it, else English. - AppKit: the OK button of
alertand of the no-passkey sheet, and everything in the open and save panels (file choosers, downloads), in the system’s language. - Chromium: its own interface (Chrome-style windows,
chrome://pages, its dialogs, its context-menu items, Inspect included), inCefRuntime.shared.locale, whichconfiguration.localizationchooses (see Languages), withconfiguration.stringOverridesfor single strings.
With the default localization, .application, both follow the app’s
language: an English-only app shows English sheets and an English
Chromium to a French user, and an app localized in French shows French
ones, once CefSwift has French strings. With .system, Chromium follows
the user’s languages while the sheets keep the app’s.
To add a language to the sheets, add
Sources/CefKit/Resources/<language>.lproj/Localizable.strings (and
Sources/CefPasskeys/Resources/… for passkeys), a copy of the English file
with its values translated, to CefSwift (a contribution, or a local copy of
the package with swift package edit). Keys are the English text; the
comment above each says where it appears and what each %@ stands for. A
string the new file lacks shows in English. cef bundle copies the bundles
into the app’s Contents/Resources; their languages do not change the
app’s CFBundleLocalizations (see Bundling).
For text of your own, in any language, replace the presenter.
HTTP authentication
When a site or proxy asks for a user name and password (Basic, Digest, NTLM), Chromium asks the page’s delegate, in both runtime styles:
func page(_ page: CefPage, credentialFor challenge: CefAuthenticationChallenge) async -> CefCredential? {
if challenge.isProxy { return CefCredential(username: "proxy-user", password: "proxy-password") }
return await CefDialogPresenter.requestCredential(for: challenge, in: page.hostWindow)
}
challenge names the full address of the request (url), the server or proxy (host,
port, isProxy), the realm and the scheme ("basic", "digest",
…). Returning nil cancels the sign-in, and the page shows what the
server sent with its 401 or 407. When the server refuses the credentials,
the delegate is asked again with the same challenge. Chromium keeps
accepted credentials for the profile and sends them again without asking.
A request that belongs to no page, such as a service worker’s, is
refused. A sign-in still waiting for an answer is cancelled when the page
navigates away or the page closes, and the default sheet dismisses
itself.
configuration.authenticationPrompt = .chromium shows Chromium’s own
dialog instead, for the whole app, and the delegate is not asked. In a
Chrome-style page the dialog is the .signIn surface
(Chromium’s own interface) and Chromium’s
password manager can fill it. In a CefWebView the load first fails with ERR_INVALID_AUTH_CREDENTIALS, reported to
page(_:didFailLoad:), and Chromium shows the dialog in a window of its
own; closing such a page leaves the page first, which dismisses that
window (Chromium crashes when the page closes under it).
Client certificates
A site can ask for a certificate to identify the user. Chromium lists the
user’s identities in the keychain whose issuers the server accepts, and by
default shows its own picker. With CefPage.Configuration.clientCertificates = .delegate, page(_:selectClientCertificateFor:) decides instead: the
CefClientCertificateRequest has the host, port and the offered
certificates; return one of them, or nil to continue without. The
default implementation asks with CefClientCertificatePresenter, a native
sheet. Private keys stay in the keychain; Chromium signs with them itself.
Navigation and new windows
page(_:decidePolicyFor:) returns .allow or .cancel for each
navigation of the main frame and of its subframes, redirects included.
A CefNavigationAction has the url, the navigating frame (as it is
before the navigation) and isMainFrame, isRedirect, hasUserGesture
and the transition: its source (.link, .explicit, .formSubmit,
.reload, .autoSubframe, .manualSubframe, …) and whether it went
isBackForward. To handle a URL yourself, cancel it and act; cancelling a
subframe’s navigation leaves the rest of the page as it is:
func page(_ page: CefPage, decidePolicyFor navigation: CefNavigationAction) -> CefNavigationDecision {
if !navigation.isMainFrame, navigation.url?.host() == "ads.example" { return .cancel }
return .allow
}
page(_:decideWindowOpenFor:) routes links with target=_blank,
window.open and ⌘-clicks. The request has targetURL, disposition
(.newForegroundTab, .newBackgroundTab, .newPopup, .newWindow, …),
features, hasUserGesture, isSourceOffscreen and isSourceChromeStyle.
Return one of:
| Action | Effect |
|---|---|
.allowNativePopup |
Chromium opens the window or tab itself. Offscreen pages cannot, so for them this acts as .openInCurrentPage, or .deny without a URL. |
.openInCurrentPage |
Loads the URL in the requesting page. |
.handled |
You opened it yourself, for example in a new CefWindow. |
.deny |
Ignores the request. |
CefWindowOpenDecision.default(for:), the default, chooses
.allowNativePopup for Chrome-style pages; for other pages it denies
a request without a user gesture, loads the URL in place, and allows a
blank popup only when the page is not offscreen. Return it for requests
you do not handle:
func page(_ page: CefPage, decideWindowOpenFor request: CefWindowOpenRequest) -> CefWindowOpenDecision {
guard request.disposition != .newPopup, let url = request.targetURL else { return .default(for: request) }
openTab(url, inBackground: !request.disposition.prefersForeground)
return .handled
}
Chromium’s popup blocker runs before the delegate in both runtime styles:
a window.open without a user gesture never reaches
decideWindowOpenFor, unless the site’s .popups setting allows popups
(the default blocks them). An app that wants to see such popups, to offer
“Show blocked popup” or to open them itself, allows the setting and decides
in the delegate. hasUserGesture reflects the document’s activation at the
time of the request, which can carry over from an earlier interaction.
profile.siteSettings.set(.allow, for: .popups, origin: URL(string: "https://example.com")!)
default(for:) then still denies them in an Alloy-style page, where
loading in place would let a script navigate the page away; a Chrome-style
page opens them.
Popups
When a page in a CefWindow opens a popup (window.open with window
features, sign-in flows) and the delegate lets Chromium open it, the popup
arrives through onPopup as a hidden CefWindow of its own, still
connected to its opener. popup.page.popupFeatures holds the origin and
size the page asked for, and popup.page.opener is the opening page.
Without onPopup, Chromium shows the popup in a window of its own design
with a location bar. When an attachment prepares the opener before its
first document, as a passkey controller does, the popup is a page
CefKit created, not connected to the opener’s page; see
Attachments.
window.onPopup = { [weak window] popup in
guard let panel = popup.window, let parent = window?.window else { return popup.show() }
if let size = popup.page.popupFeatures?.size, size.width > 0, size.height > 0 {
panel.setContentSize(size)
}
panel.tabbingMode = .disallowed
parent.addChildWindow(panel, ordered: .above) // layered over its opener
popup.show()
}
A popup closes when its page calls window.close(). It stays open when its
opener closes unless you close it, for example from the opener’s onClose.
Links to other apps
A URL whose scheme Chromium does not load itself, such as mailto:,
zoommtg: or slack:, reaches
page(_:decideExternalProtocolFor:) with a
CefExternalProtocolRequest: the url, the frameURL that asked, and
whether it isMainFrame. Return .allow to open it with the app macOS
has for the scheme (request.applicationURL), or .deny. In both runtime
styles Chromium never opens another app itself. The default asks with
CefExternalProtocolPresenter’s sheet (“Open “Zoom”?”, naming the site),
and denies without asking when no app handles the scheme:
func page(_ page: CefPage, decideExternalProtocolFor request: CefExternalProtocolRequest) async
-> CefExternalProtocolDecision
{
if request.url.scheme == "mailto" { return .allow }
return await CefExternalProtocolPresenter.present(request, in: page.hostWindow)
}
The question is cancelled, and its sheet dismissed, when the page navigates away.