The JavaScript bridge
Evaluate scripts, call typed Swift functions from the page, send events back, and add user scripts and style sheets.
struct Person: Codable { var name: String }
let bridge = CefBridge(name: "app")
bridge.handle("greet") { (person: Person) in "Hello, \(person.name)!" }
var pageConfiguration = CefPage.Configuration()
pageConfiguration.bridges = [bridge]
let page = CefPage(url: url, configuration: pageConfiguration)
let count = try await page.evaluateJavaScript("document.links.length").intValue
In the page: const reply = await app.greet({ name: "Ada" }).
Gallery: BridgeDemo, EvaluateJavaScriptDemo, UserScriptsDemo, FramesDemo.
JavaScript
let count = try await page.evaluateJavaScript("document.links.length").intValue
let size = try await page.evaluateJavaScript("({w: innerWidth, h: innerHeight})", as: Size.self)
evaluateJavaScript(_:) runs in the main frame’s own JavaScript context,
waits for a returned promise, and returns the value as CefJSON. The as:
form decodes it into any Decodable type. An exception thrown by the script
arrives as CefJavaScriptError, and so does a navigation that replaces the
page before the result is ready. executeJavaScript(_:) runs a script
without waiting for a result.
A script that may never settle takes a timeout. When it runs out, the
call throws CefError.timedOut; only the wait ends, and the script, with
any promise it returned, goes on running in the page:
do {
let ready = try await page.evaluateJavaScript("app.whenReady()", as: Bool.self, timeout: .seconds(5))
print(ready)
} catch CefError.timedOut {
print("still waiting for the page")
}
The frame variants, evaluateJavaScript(_:in:timeout:) and
evaluateJavaScript(_:as:in:timeout:), take one too.
Some web APIs need a user gesture: opening a popup, entering fullscreen,
starting audio, a beforeunload prompt. evaluateJavaScript(_:userGesture: true) runs the script as if the user had just clicked. Only the DevTools
Protocol can do that, so it attaches devTools to the page; see
Compatibility with bot protection.
In Chromium 158, a gesture-based fullscreen request also requires the page
view to have keyboard focus. Focus the hosted view before evaluating the script.
Frames
page.frames lists the page’s frames connected to a renderer: the main
frame first, then each iframe in the order it attached. mainFrame is
the top-level one. Each CefFrame has an id, its url, the name of
its iframe, isMain, its parent’s parentID, and its origin: what the
browser process establishes from its own record of the frame’s address,
as the bridge does for its callers (about:blank and srcdoc frames have
their parent’s, nil when the address gives an opaque one). The list is
observable and follows Chromium’s frame events: an iframe appears when it
attaches and goes when it is removed, and a frame’s url follows its
navigations. A cross-site navigation of the main frame replaces it with a
new frame.
for frame in page.frames where !frame.isMain {
let title = try await page.evaluateJavaScript("document.title", in: frame)
print(frame.url as Any, title)
}
evaluateJavaScript(_:in:) and executeJavaScript(_:in:) run a script in
one frame, cross-site frames in other renderer processes included, as the
main-frame versions do. An evaluation in a frame that is gone, or that
goes while the script runs, throws CefError.frameDetached.
text(of:) and source(of:) read a frame’s text (as innerText renders
it) and its HTML (the document as it is now, serialized) natively from
the renderer, without running script in the page; with no frame, the main
frame’s:
let words = try await page.text().split(whereSeparator: \.isWhitespace).count
load(_:) also takes a URLRequest, to send a method, headers and a
body (httpBody), as a form posting would. CEF allows it only from a
page of the request’s own origin (otherwise Chromium ends the renderer),
so the navigation fails at once, sending nothing, unless the main frame
is already on that origin:
var request = URLRequest(url: URL(string: "https://example.com/search")!)
request.httpMethod = "POST"
request.httpBody = Data("q=chromium".utf8)
try await page.load(request).waitUntilLoaded()
User scripts and style sheets
User scripts run in every document, before the page’s own scripts: a profile’s in every page of the profile, Chromium’s own included, and a page’s own after them:
profile.userScripts = [CefUserScript(source: "window.appVersion = '1.2'")]
pageConfiguration.userScripts = [
// At document start the page has no <body> yet; this one waits for it.
CefUserScript(source: "document.body.dataset.app = 'yes'", matching: ["https://*.example.com/*"],
excluding: ["https://login.example.com/*"], injectionTime: .documentEnd),
.styleSheet("header { display: none }", matching: ["https://news.example/*"]),
]
matching:limits a script to URLs that match one of the patterns as a whole, where*stands for any run of characters, andexcluding:keeps it out of URLs that match one of those. A script with either list runs inside a function, so its top-level declarations are not global.injectionTime: .documentEndruns the script when the document has been parsed (DOMContentLoaded), before the page’s own listeners for it.frames: .mainFrameruns it in top-level documents only; by default it runs in every frame, cross-site frames included.- Scripts share the page’s globals: CEF’s API has no isolated worlds.
CefUserScript.styleSheet(_:matching:includingShadowRoots:)adds CSS. WithincludingShadowRoots(the default) its rules also apply inside every shadow root, including roots whose component sets its ownadoptedStyleSheets.page.addUserScript(_:)adds a script after creation andpage.removeUserScript(_:)takes one of the page’s own away; a change toprofile.userScriptsreaches every page of the profile. Each applies from the next document on: a document already loaded keeps what a removed script, or a removed style sheet, did until it reloads.- A page in a window Chromium opens by itself (a ⌘-clicked link from a
Chrome-style window,
chrome.windows.create, a tab dragged out) has no CefKitextra_info, and CEF connects its frames only once their first document has committed: its profile’s scripts and bridges apply from its second document on. Native popups, and tabs Chromium opens inside a window CefKit made, get them from the first. - An exception a user script throws is logged on the page’s console as
CefUserScript: <message> (line <n>), whichpage(_:didLog:)receives.
A selector cannot cross a shadow boundary, even when the rules reach inside
shadow roots. If #row lives in the shadow root of settings-section, the
selector settings-section #row matches nothing; write #row.
Bridge
CefBridge exposes Swift methods to JavaScript as functions that return
promises. Arguments and results are JSON’s kinds of values plus bytes, so
any Codable type works, and an ArrayBuffer argument or a Data result
travels as bytes: an ArrayBuffer in the page, Data in Swift. Typed
arrays reach Swift as objects; pass their buffer.
struct Person: Codable { var name: String }
let bridge = CefBridge(name: "app")
bridge.handle("greet") { (person: Person) in "Hello, \(person.name)!" }
bridge.handle("save") { (document: Document, call: CefBridge.Call) in
guard call.origin == "https://app.example.com" else { throw AppError.forbidden }
try documents.save(document)
}
var pageConfiguration = CefPage.Configuration()
pageConfiguration.bridges = [bridge]
// Or for every page of a profile, Chromium's own included:
profile.bridges = [bridge]
const reply = await app.greet({ name: "Ada" });
const stop = app.on("themeChanged", theme => apply(theme));
- The global exists before any page script runs, in every frame
accesspermits, cross-site frames and popups included. - A handler that throws rejects the promise.
bridge.emit("themeChanged", theme)delivers an event toapp.onlisteners, in the top-level document of every page the bridge is attached to or of one (to: page), andbridge.emit(_:_:to:in:)to one frame, such as the one a call came from (call.frame).- A page’s own bridge of the same name as one of its profile’s takes its place in that page.
CefBridge.Calldescribes the caller:page,method,originandframe, the callingCefFrame. The browser process establishes the origin from its own record of the frame’s address, so neither a page nor a compromised renderer can claim another one.about:blankandsrcdocframes have their parent’s origin and ablob:document the origin in its address. Where the address cannot confirm an origin (data:documents, sandboxed ones, a popup’s firstabout:blank) the origin is"null", which no.originslist matches.- Values travel as
JSON.stringifywould write them: own enumerable properties, read through the page’s getters. A getter that throws rejects the call with its exception instead of sending part of the value. Values nest at most 64 deep, and a call’s payload holds at most 1 GiB and 16 Mi values; past those, the call is rejected.
Handlers run with your app’s privileges, so bridge.access decides where
the global exists:
| Access | Documents that get the bridge |
|---|---|
.mainFrame (default) |
Top-level documents. |
.origins(["https://app.example.com"]) |
Documents from the listed origins, in any frame, including their about:blank, srcdoc and blob: subframes. Never data: or sandboxed documents. "file://" matches a top-level file: page only, not file: subframes or frames inside them, since CEF cannot tell a sandboxed one apart; the same holds for custom schemes registered with .local. A custom scheme without .standard has no origin to list. |
.anyFrame |
Every document. Use it only for pages that show nothing but your own content. |
A document outside access has no global and no way to reach the bridge.
Calls are checked again in Swift against the caller’s origin and frame. A change to access applies to calls at once and to
the global from the next document load:
bridge.access = .origins(["app://start"]) // only your start page
Page-facing features
A page can tell a browser apart from a stock one by what it can observe:
globals it did not define, scripts it did not load, a debugger that stops
it, or a DevTools session that changes how console behaves. So features
that reach into pages run in the renderer, through the helper’s own code,
and the DevTools Protocol is used only for what nothing else offers.
The renderer side. The helper executable is Swift
(Sources/CefHelper, Sources/CefRenderer). It gives cef_execute_process
an app whose render process handler drives a list of
CefRendererExtensions, each with hooks for a page’s arrival in the
process (with the extra_info it was created with), each JavaScript
context created and released, and process messages whose names start with
its prefix. Everything runs on the renderer’s main thread, which on macOS
is the process’s main thread, so extensions are @MainActor and CEF’s
callbacks enter it with MainActor.assumeIsolated. V8Value, V8Context
and V8Exception wrap the V8 C API; CefProcessMessage (in CefBase,
shared with the browser process) is a message’s name and plain arguments.
A later renderer-side feature is one more extension type.
MediaShim is the extension behind services.systemMediaDecoders
(System media decoders). Three
processes take part, and only one of them parses the page’s audio:
renderer (MediaShim) demux MP4 / ADTS → packets + times wire payload, shared memory
│ cefswift.media.decode
browser (CefMediaDecoding) relays the bytes, reads nothing NSXPCConnection
│ decodeAudio(…)
<App> Media.xpc AudioToolbox → FLAC in fragmented MP4 App Sandbox, no entitlement
│ [Data] segments → cefswift.media.decoded
renderer one native appendBuffer per page append Chromium's own element and clock
- The browser process passes
--cefswift-media-shimto renderers only when the option is on and the bundle has the service (CefMediaDecoding.isAvailable), and the helper registers the extension only then. When a document’s main world is created, before its scripts, the extension runsMediaShimScript, which evaluates to a function, and calls it with a native object ofdecode,releaseandfunction; the page’s globals gain nothing. The script is generated fromSources/CefRenderer/MediaShim/*.jsbyScripts/generate-media-shim.py, which CI runs with--check. function(name, implementation)makes a native function (cef_v8_value_create_function) that calls the JavaScript implementation withset_rethrow_exceptions, so what the replacedMediaSource,SourceBuffer,HTMLMediaElementandMediaCapabilitiesmembers throw reaches the page as thrown (aDOMException, Chromium’s ownTypeError), andFunction.prototype.toStringprints[native code].addSourceBufferfor a system type returns Chromium’s ownaudio/mp4; codecs="flac"SourceBuffer; the replacedSourceBuffer.prototypemembers change only what such a buffer does with an append: demux it, send its packets with their times, and append the service’s answer in one nativeappendBuffer, so the page sees oneupdatestart,updateandupdateendper append.- Chromium’s sandbox keeps AudioToolbox’s decoders out of renderers
(
AudioConverterNewreturns'fmt?'), and the browser process is not sandboxed, so the service is an XPC service of its own (Sources/CefMediaService, productcefswift-media), signed withcom.apple.security.app-sandboxalone. It keeps oneAudioStreamper stream (decoder, timeline, FLAC writer), named by frame identifier and the renderer’s stream number, at most 32, the least recently used dropped. The decoder writes planar big-endian samples straight into the planes that become FLAC’s verbatim subframes; the browser process hands the payload’s memory to XPC without a copy and the service’s segments to a shared memory region with one. - Video (
.video, the switch’s valueaudio,video) takes the same path withcefswift.media.decodeVideo: the service decodes H.264 or HEVC withVTDecompressionSessionand replies with the frames asIOSurfaces, which XPC moves without a copy. The browser process passes the surfaces on to the renderer that asked, also without a copy, over a Mach port of the renderer’s (below); a renderer without one gets each frame copied into the reply’s shared memory, after which the service may reuse them (releaseFrames). The renderer encodes the frames as VP9 with WebCodecs (video.js), writes fragmented MP4 itself (fmp4.js) and appends it to a nativevp09SourceBuffer; a buffer of video and AAC is one nativevp09,flacbuffer whose FLAC track is the service’s, renumbered. Design notes have the costs. - By default (
directin the switch’s value) a<video>without native controls skips the VP9 encode (presenter.js): itssrcObjectis aMediaStreamTrackGeneratorthe shim writes the decoded frames to, and a clock element the shim makes, never in the document, plays the page’s MediaSource (or the shim’s, for a file) with the sound and a placeholder VP9 track of 64×64 black key frames at the source’s times. The page’s element forwards its time, state, methods and media events to the clock element. The frames are written by a worker the shim starts (from ablob:URL), which holds the generator’s stream: the main thread copies each frame into aVideoFramea little ahead and transfers it, with the clock’s time and the animation frames’ times, and the worker writes it halfway between two refreshes when it is due. Where a page’s CSP refuses the worker, the main thread writes the frames at animation frames. Design notes have the costs and what a page can tell. - The frame port: CEF’s process messages carry bytes, and a sealed
renderer can look no Mach service up. So with
.videothe browser process registers a bootstrap name (CefMediaFramePorts, passed in thecefswift-media-framesswitch), and each renderer, inCefHelperStartupbefore it seals its sandbox, makes a receive right and sends a send right to it there; the browser process keeps it only from a child of its own (the message’s audit token). AdecodeVideorequest carries the renderer’s process identifier; the reply’s frames go to that port, one Mach message each with the surface’s port, ahead of the CEF message with their times and thesurfacesmarker. The renderer (MediaFrames) looks each surface up, marks it in use (IOSurfaceIncrementUseCount, which keeps the decoder’s pool from reusing it), and hands the page script a handle; the script copies the frame into an ArrayBuffer only when it shows or encodes it (copyFrame), so frames decoded ahead stay in the service’s surfaces. The service releases a reply’s frames when the stream’s next request arrives, by which time the renderer holds them. cefswift.media.prepare, sent by the shim when a page sets a media file as asrcor asks about a type the shim plays, starts the service and opens one VideoToolbox session there, which the first frame would otherwise wait for.
PageScripting is the extension behind bridges, user scripts and
evaluateJavaScript:
-
A page’s bridges and user scripts, its profile’s and its own, travel as JSON in the
extra_infoof its creation (cef_browser_host_create_browser,cef_browser_view_create, andon_before_popupfor popups). CEF handsextra_infoto every renderer process that shows a frame of the page, before that frame’s first document starts, so nothing waits on a message and no first document runs onabout:blank. A page Chromium creates in a window of its own has noextra_info; its configuration reaches each renderer as the page’s frames attach (on_frame_attached), which CEF reports once a frame’s first document has committed, so that document goes without. -
When a context is created in a frame’s main world, the user scripts that match run with
cef_v8_context_t.eval, as scripts without a URL; scripts for document end run from aDOMContentLoadedlistener added first. -
A bridge is a global object whose named-property interceptor answers
invoke,on,offand any other name with a native function. A call creates a promise, sendscefswift.page.callwith the argument and the document’s origin (self.origin, read as the context is created), and the reply resolves or rejects it. V8 values are read and made through the V8 API, straight into and out of the message (Data paths), with noJSONobject or injected script; the page’s getters,Proxytraps andObject.keysrun as they would forJSON.stringify. Cross-site frames run in other renderer processes, which get the configuration with the page, soaccessdecides for them as for any frame. -
The browser process does not take the renderer’s word for the origin. It establishes the caller’s origin from its own record of the frame’s committed address (
cef_frame_t.get_urlin the browser process) and checks the caller’s frame and that origin againstaccessbefore a handler runs (CefBridge.establishedOrigin):Frame’s address Established origin Scheme, host and port ( https:,http:, a standard custom scheme)The address’s origin, if the renderer reports it; "null"if the renderer reports"null"(a sandboxed document); anything else rejects the callblob:https://host/…,filesystem:https://host/…The origin they name, checked the same way; blob:null/…is opaquefile:, or a custom scheme registered with.local, in the main framefile://(ormyapp://host), checked the same wayfile:or.localin a subframeOpaque about:blank,about:srcdocin a subframeThe nearest ancestor’s established origin, checked the same way; opaque under a file:or.localdocumentabout:blankat the top (a popup’s first document)Opaque: CEF does not expose the frame that opened it data:,javascript:, otherabout:pages, any other address without a host (a custom scheme without.standard), an unparseable or missing oneOpaque An opaque origin is reported to handlers as
"null"and never matches.origins(...), even when"null"is listed;.mainFrameand.anyFramedo not look at origins.The renderer reports
self.origin, the document’s own origin, notlocation.origin, the address’s: they differ forabout:blankandsrcdoc, which have their parent’s origin but an opaque address. Forfile:and.localschemes it is the other way round: Chromium 156 gives every such document an opaqueself.origin("null") whilelocation.originisfile://(or the address’s). The renderer then reportslocation.originfor a main frame only. A main frame cannot be sandboxed by an embedding page, but a subframe can, and neither CEF in the browser process norself.originin the renderer tells a sandboxedfile:subframe from another, sofile:and.localsubframes, and theirsrcdocandabout:blankchildren, are opaque. A.localscheme’s own handler could still sandbox a main frame with aContent-Security-Policy: sandboxheader, which this does not detect;file:documents have no headers.The renderer installs an
.originsbridge by the same rules where it can (it leaves out a top-levelabout:document), so a document refused in the browser process normally has no global at all. -
evaluateJavaScriptsendscefswift.page.evaluateto the main frame, whose renderer runs the script in the main world and sends the value back the same way. A returned promise is awaited through itsthen. -
Changes after creation (
addUserScript,removeUserScript, a profile’suserScriptsorbridges,CefBridge.access) go as acefswift.page.configuremessage to every frame of the page, and to each frame that attaches later. A renderer process reports its configuration generation (-1 for none) the first time it sees one of the page’s documents, and gets the current one if it differs. Generations come from one counter for every page, so a configuration made later is always newer than any a renderer has.
Two CEF 156 behaviors shape this code. A message from the browser process
is handled inside a scope that defers promise jobs, and Blink does not run
them at the end of that task, so after settling a promise the renderer
enters the context again from a task of its own, whose exit runs them. And
a native function created outside a V8 callback, as in a message handler,
never reaches its Swift side when called; such functions are looked up
through an interceptor on each call (V8Context.durableFunction).
What still uses the DevTools Protocol. CefDevTools attaches a DevTools
message observer to the page and speaks the protocol in-process. CEF
attaches the session on the first message and keeps it until the page
closes. An attached session with no domain enabled changes nothing a page
can measure; enabled domains do (see the guide’s “Compatibility with bot
protection”). These use it:
| Feature | Protocol use |
|---|---|
page.devTools |
Whatever the app sends. |
evaluateJavaScript(_:userGesture: true) |
Runtime.evaluate with userGesture, the only way to grant a user activation. |
snapshot() |
Page.captureScreenshot, for windowed pages; an offscreen page’s snapshot is the frame its view shows. |
CefPasskeys’ CefPasskeyController |
WebAuthn, Debugger, Page and Runtime enabled for the page’s lifetime; see Passkeys. |
discard(), discardBlockers() |
DOMDebugger.getEventListeners on every frame’s window, to find a beforeunload listener, which JavaScript cannot list: the main frame’s window from Runtime.evaluate, a same-process subframe’s from Page.getFrameTree, DOM.getFrameOwner, DOM.describeNode, DOM.resolveNode and Runtime.callFunctionOn (defaultView), a cross-site frame’s the same way in a session of its own (Target.getTargets, Target.attachToTarget with flatten, Target.detachFromTarget). No domain is enabled. |
| Offscreen accessibility actions | Accessibility.enable for the length of one lookup, then DOM.focus, DOM.scrollIntoViewIfNeeded; Input.insertText only for a field that takes no input-method text. |
A page created again after a discard enables the domains its session had enabled before, before its page loads; a session that was never used stays unattached.
Bridge and evaluation transport
Bridge calls and evaluateJavaScript carried JSON text in process
message strings: the renderer built a tree of the V8 value and wrote it
as text, the browser process parsed the text into CefJSON with
JSONDecoder, then encoded that tree with JSONEncoder and decoded it
again into the handler’s type; results went back the same way, through
cef_parse_json and a second tree in the renderer. Data became base64
text and an ArrayBuffer an empty object. They carry the wire format in
Data paths instead.
Measured with SelfTest -benchmark bridge, evaluate and codec on
2026-11-13, on AC power, Low Power Mode off, other apps open, the two
builds back to back; the second of two runs. Calls are sequential, each
awaited before the next. Allocations are those of the app’s main thread,
counted through malloc_logger; the renderer’s are not counted.
| Bridge call | JSON: calls a second | Allocations a call | Wire: calls a second | Allocations a call |
|---|---|---|---|---|
ping(Int) -> Int |
14 700 | 90 | 18 500 | 38 |
| 20-field struct, both ways | 4 560 | 559 | 13 100 | 53 |
| 10 000 small structs, both ways | 3.0 | 1 290 375 | 26.7 | 30 076 |
16 MB ArrayBuffer in |
not possible | 529 (1.9 ms) | 42 | |
16 MB Data out |
0.75 (1.33 s, as base64) | 352 | 253 (3.95 ms) | 47 |
| 16 MB as base64 text in | 1.55 (645 ms) | 463 | 35 (28.7 ms) | 48 |
evaluateJavaScript |
JSON: calls a second | Allocations | Wire: calls a second | Allocations |
|---|---|---|---|---|
Int |
17 600 | 51 | 20 900 | 23 |
| 20-field object as a struct | 5 380 | 284 | 15 900 | 26 |
10 000-element array as [Struct] |
6.1 | 640 171 | 40 | 10 042 |
The same as CefJSON |
7.4 | 490 097 | 44 | 10 023 |
In-process codec cost (-benchmark codec, same build, per value):
| Value | JSON decode | Wire decode | JSON encode | Wire encode |
|---|---|---|---|---|
Int |
2.0 µs, 20 allocations | 0.13 µs, 1 | 2.9 µs, 22 | 0.27 µs, 4 |
| 20-field struct | 42 µs, 252 | 2.2 µs, 4 | 51 µs, 257 | 2.0 µs, 15 |
| 10 000 small structs | 100 ms, 640 119 | 5.1 ms, 10 020 | 118 ms, 650 121 | 4.3 ms, 20 017 |
What remains per call is mostly Chromium’s: the message, its argument
list and binary value, the frame wrapper and its address, which the
origin check parses, and a Task for the handler. Decoding allocates
one container per struct (Codable’s KeyedDecodingContainer box) and
a string longer than 15 UTF-8 bytes. The wire form is 10 to 30% larger
than JSON text (fixed-width lengths and counts), which no measurement
showed a cost for.
Below 64 KB a payload travels in a cef_binary_value_t; above, in
shared memory, whose region costs a mapping on each side but saves
Chromium’s copy of the argument list. A 16 MB ArrayBuffer argument is
copied once, into the region; the handler’s Data is the region.