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

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, and excluding: 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: .documentEnd runs the script when the document has been parsed (DOMContentLoaded), before the page’s own listeners for it.
  • frames: .mainFrame runs 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. With includingShadowRoots (the default) its rules also apply inside every shadow root, including roots whose component sets its own adoptedStyleSheets.
  • page.addUserScript(_:) adds a script after creation and page.removeUserScript(_:) takes one of the page’s own away; a change to profile.userScripts reaches 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 CefKit extra_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>), which page(_: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 access permits, cross-site frames and popups included.
  • A handler that throws rejects the promise.
  • bridge.emit("themeChanged", theme) delivers an event to app.on listeners, in the top-level document of every page the bridge is attached to or of one (to: page), and bridge.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.Call describes the caller: page, method, origin and frame, the calling CefFrame. 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:blank and srcdoc frames have their parent’s origin and a blob: document the origin in its address. Where the address cannot confirm an origin (data: documents, sandboxed ones, a popup’s first about:blank) the origin is "null", which no .origins list matches.
  • Values travel as JSON.stringify would 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-shim to 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 runs MediaShimScript, which evaluates to a function, and calls it with a native object of decode, release and function; the page’s globals gain nothing. The script is generated from Sources/CefRenderer/MediaShim/*.js by Scripts/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 with set_rethrow_exceptions, so what the replaced MediaSource, SourceBuffer, HTMLMediaElement and MediaCapabilities members throw reaches the page as thrown (a DOMException, Chromium’s own TypeError), and Function.prototype.toString prints [native code].
  • addSourceBuffer for a system type returns Chromium’s own audio/mp4; codecs="flac" SourceBuffer; the replaced SourceBuffer.prototype members 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 native appendBuffer, so the page sees one updatestart, update and updateend per append.
  • Chromium’s sandbox keeps AudioToolbox’s decoders out of renderers (AudioConverterNew returns 'fmt?'), and the browser process is not sandboxed, so the service is an XPC service of its own (Sources/CefMediaService, product cefswift-media), signed with com.apple.security.app-sandbox alone. It keeps one AudioStream per 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 value audio,video) takes the same path with cefswift.media.decodeVideo: the service decodes H.264 or HEVC with VTDecompressionSession and replies with the frames as IOSurfaces, 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 native vp09 SourceBuffer; a buffer of video and AAC is one native vp09,flac buffer whose FLAC track is the service’s, renumbered. Design notes have the costs.
  • By default (direct in the switch’s value) a <video> without native controls skips the VP9 encode (presenter.js): its srcObject is a MediaStreamTrackGenerator the 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 a blob: URL), which holds the generator’s stream: the main thread copies each frame into a VideoFrame a 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 .video the browser process registers a bootstrap name (CefMediaFramePorts, passed in the cefswift-media-frames switch), and each renderer, in CefHelperStartup before 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). A decodeVideo request 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 the surfaces marker. 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 a src or 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_info of its creation (cef_browser_host_create_browser, cef_browser_view_create, and on_before_popup for popups). CEF hands extra_info to 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 on about:blank. A page Chromium creates in a window of its own has no extra_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 a DOMContentLoaded listener added first.

  • A bridge is a global object whose named-property interceptor answers invoke, on, off and any other name with a native function. A call creates a promise, sends cefswift.page.call with 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 no JSON object or injected script; the page’s getters, Proxy traps and Object.keys run as they would for JSON.stringify. Cross-site frames run in other renderer processes, which get the configuration with the page, so access decides 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_url in the browser process) and checks the caller’s frame and that origin against access before 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 call
    blob:https://host/…, filesystem:https://host/… The origin they name, checked the same way; blob:null/… is opaque
    file:, or a custom scheme registered with .local, in the main frame file:// (or myapp://host), checked the same way
    file: or .local in a subframe Opaque
    about:blank, about:srcdoc in a subframe The nearest ancestor’s established origin, checked the same way; opaque under a file: or .local document
    about:blank at the top (a popup’s first document) Opaque: CEF does not expose the frame that opened it
    data:, javascript:, other about: pages, any other address without a host (a custom scheme without .standard), an unparseable or missing one Opaque

    An opaque origin is reported to handlers as "null" and never matches .origins(...), even when "null" is listed; .mainFrame and .anyFrame do not look at origins.

    The renderer reports self.origin, the document’s own origin, not location.origin, the address’s: they differ for about:blank and srcdoc, which have their parent’s origin but an opaque address. For file: and .local schemes it is the other way round: Chromium 156 gives every such document an opaque self.origin ("null") while location.origin is file:// (or the address’s). The renderer then reports location.origin for 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 nor self.origin in the renderer tells a sandboxed file: subframe from another, so file: and .local subframes, and their srcdoc and about:blank children, are opaque. A .local scheme’s own handler could still sandbox a main frame with a Content-Security-Policy: sandbox header, which this does not detect; file: documents have no headers.

    The renderer installs an .origins bridge by the same rules where it can (it leaves out a top-level about: document), so a document refused in the browser process normally has no global at all.

  • evaluateJavaScript sends cefswift.page.evaluate to 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 its then.

  • Changes after creation (addUserScript, removeUserScript, a profile’s userScripts or bridges, CefBridge.access) go as a cefswift.page.configure message 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.

Was this page helpful?