---
title: "Extensions"
description: "Chrome's extension system: the Web Store, the profile's extensions, extensions the app ships, and their toolbar actions."
---

```swift
import CefChromium

for item in try await profile.extensions.refresh() {
    print(item.name, item.version, item.isEnabled)
}
```

Gallery: [`ExtensionsDemo`](https://github.com/Rajaniraiyn/CefSwift/blob/main/Examples/Sources/Gallery/Demos/ExtensionsDemo.swift).
Browser example: [`Features/Extensions`](https://github.com/Rajaniraiyn/CefSwift/tree/main/Examples/Sources/Browser/Features/Extensions) shows pinned actions, their popups and a Manage Extensions window.

## Extensions

Chrome style runs Chrome's own extension system: extensions users install
from the Chrome Web Store or `chrome://extensions`, and ones the app
installs. CefSwift ships no extension of its own.

What works where, in CEF 156 (SelfTest's `extensions` group checks each
row with a test extension):

| | `openChromeWindow` (Chrome's window) | `CefWindow` | Alloy views (`CefWebView`, offscreen) |
|---|---|---|---|
| Content scripts, `declarativeNetRequest`, `webRequest` | yes | yes | yes |
| Background service worker, `storage`, `cookies`, `bookmarks`, `history`, `downloads`, `alarms`, `offscreen`, native messaging | yes | yes | (runs for the profile) |
| `chrome.tabs` / `chrome.windows` | real tabs and windows | each `CefWindow` is a `popup`-type window of one tab | not listed as tabs |
| `chrome.tabs.group`, `tabs.move`, `chrome.tabGroups` | yes | refused ("Tabs can only be moved to and from normal windows") | — |
| `tabs.create`, `windows.create`, `runtime.openOptionsPage()` | adds a tab to that window | opens a Chrome window → `onChromeTab` | — |
| Action popups (toolbar button, `chrome.action.openPopup()`) | yes | no: Chromium has no toolbar for popup-type windows | no |
| Chrome's extensions menu (puzzle piece) | yes | with `toolbar: .chrome` | no |
| Context-menu items extensions add | yes | yes, in `CefContextMenu` | yes |
| `chrome_url_overrides` (new tab page) | Chrome's new tabs | `chrome://newtab` loads | — |
| Chrome Web Store "Add to Chrome" | yes | yes | no |

The store's page says "Switch to Chrome to install extensions" because
CEF's user agent names Chromium, not Google Chrome; Add to Chrome works
regardless, through the store's own `chrome.webstorePrivate` API, and shows
Chromium's install dialog ("Add “…”?") over the window, a surface of kind
`.extensionInstallPrompt`. No user agent change is needed or made.

### The profile's extensions

With `CefChromium`, `profile.extensions` is Chromium's list for a profile,
observable:

```swift
import CefChromium

let extensions = profile.extensions
for item in try await extensions.refresh() {
    print(item.name, item.version, item.isEnabled, item.installSource)
}
try await extensions.setEnabled(false, for: "ddkjiahejlhfcafbddmgiahcphecmpfh")
try await extensions.setAllowedInIncognito(true, for: "ddkjiahejlhfcafbddmgiahcphecmpfh")
try await extensions.checkForUpdates()
for await _ in extensions.changes { print(extensions.installed.count) }
```

- `installed` is the list as last read, sorted by name, and stays current
  while the app uses it: after each change made through this API, and as
  Chromium reports installs, updates and removals, the user's in Chrome's
  interface included. A SwiftUI view that reads it updates by itself.
- A `CefExtension` has its `id`, `name`, `version`, `description`, `icon`,
  `state` (`.enabled`, `.disabled`, `.terminated`, `.blocklisted`),
  `installSource` (`.webStore`, `.unpacked`, `.external`, `.policy`, …),
  `permissionWarnings` (the lines Chrome shows), `hosts` and `siteAccess`,
  `isAllowedInIncognito`, `optionsURL`, `homepageURL`, `webStoreURL`,
  `commands` (with their shortcuts), `action` and `replacedPages`.
- `action` is the toolbar action its manifest declares: `title`,
  `popupURL` and `icon`. What an extension sets later per tab (badge text,
  title, icon) Chromium keeps to itself and its own toolbar: no API reads
  it, so an app's toolbar shows the declared action.
- `replacedPages[.newTab]` is the page an extension puts in place of the
  new tab page (`chrome_url_overrides`). Chromium shows it for
  `chrome://newtab`; an app with a start page of its own decides whether to
  open that instead.
- `uninstall(_:)` removes an extension without asking: ask first, as
  Chrome does. `setSiteAccess(_:for:)`, `setPinnedToToolbar(_:for:)`,
  `reload(_:)`, and developer mode: `setDeveloperModeEnabled(_:)`,
  `loadUnpacked(at:)` (Chrome's "Load unpacked") and `pack(_:privateKey:)`
  (its "Pack extension", which writes a `.crx` and its key).
- Incognito profiles share the default profile's extensions, which run
  there only when allowed. CEF's `CefProfile.incognito()` is an in-memory
  profile of its own, and extensions allowed in incognito did not run in
  it in SelfTest; they do in Chrome's own incognito windows.

### Installing extensions with the app

`CefRuntime.Configuration.extensions` installs extensions in every
profile, incognito ones aside:

```swift
var configuration = CefRuntime.Configuration.chrome
configuration.extensions = [
    // Downloaded from the Chrome Web Store in the background on first start.
    .webStore("ddkjiahejlhfcafbddmgiahcphecmpfh"),
    // A package the bundle carries (cefapp.json "extensions"), installed
    // without a download.
    .package(at: Bundle.main.resourceURL!.appendingPathComponent("Extensions/Helper.crx"),
             id: "kpdaoijgjogphaiahlmcjhhfknhnllkc", version: "1.0"),
    // An unpacked directory, loaded at every start as a developer's.
    .unpacked(at: Bundle.main.resourceURL!.appendingPathComponent("Extensions/DevExtension")),
]
```

- `.webStore` and `.package` use Chromium's mechanism for extensions other
  programs install: CefKit writes `External Extensions/<id>.json` in the
  root cache directory, which Chromium reads at start-up. Chromium installs
  such an extension disabled until it is accepted; `profile.extensions`
  accepts the configured ones the first time it reads the list, once, so a
  user who turns one off later keeps it off. Users can remove them, and
  Chromium does not install a removed one again. Taking an extension out
  of the configuration removes CefKit's file for it, and Chromium then
  treats it as withdrawn by the program that added it.
- Until Chromium has installed one, its identifier is in
  `profile.extensions.pendingInstallations`. Chromium reports no progress
  and no failure for these: offline, or with an identifier the store does
  not have, it stays pending, and Chromium tries again at its next start
  and on its update schedule.
- `.webStore` extensions update as store installs do. A `.package`
  installs again when its `version` changes.
- To ship one in the bundle, list it in `cefapp.json`'s `extensions`
  (`"extensions": ["Extensions/Helper.crx"]`), or Xcode's `CEF_EXTENSIONS`
  build setting: both tracks copy `.crx` packages and unpacked directories
  into `Contents/Resources/Extensions`, which the app's signature seals.
  `cef doctor` reads each: a package's identifier from its CRX3 header,
  checked against its key; a directory's manifest, and its identifier
  from its `key` (without one, Chromium derives the identifier from the
  install path, which moves with the app). It warns about code inside one.
  Make a `.crx` with `chrome://extensions`' Pack extension or
  `profile.extensions.pack(_:privateKey:)`, and keep the key.
- `.unpacked` uses `--load-extension`. Chromium 156 still honours it in
  CEF (Chrome stopped in its branded builds); the extension is listed as a
  developer's and comes back at each start even if removed.
- Enterprise policy (`ExtensionInstallForcelist`, `ExtensionSettings`)
  applies through `enterprisePolicy` only when it is mandatory: set by a
  configuration profile or `/Library/Managed Preferences`. Chromium
  rejects these policies as recommended values (`defaults write`), which
  is all an app can write itself, so they are for administrators, not for
  apps; `chrome://policy` shows them as errors otherwise.

### Toolbars, popups and the Web Store

In windows with Chrome's toolbar (`openChromeWindow`, and a `CefWindow`
with `toolbar: .chrome`), Chrome's extensions button and menu work as in
Chrome; the menu is a surface of kind `.extensionsMenu`, and an action's
popup `.extensionPopup`, which CefChromium anchors and dismisses like its
other surfaces.

An app's own toolbar lists `installed` and shows each `action.icon`. For
the popup, Chromium offers no way to open an extension's popup in a window
without its toolbar, so the Browser example shows the action's `popupURL`
in a small Chrome-style window of its own under the button
(`Examples/Sources/Browser/Features/Extensions`): the popup runs with the
extension's APIs, but its "current window" is its own and the click grants
no `activeTab`.

```swift
import CefChromium
import SwiftUI

struct ExtensionButtons: View {
    let extensions: CefExtensions
    let open: (URL) -> Void

    var body: some View {
        ForEach(extensions.installed.filter { $0.isEnabled && $0.action != nil }) { item in
            Button {
                if let popup = item.action?.popupURL { open(popup) }
            } label: {
                if let icon = item.action?.icon ?? item.icon { Image(nsImage: icon) }
            }
            .help(item.action?.title ?? item.name)
        }
    }
}
```

### Native messaging hosts

Password managers and other desktop apps talk to their extensions through
native messaging hosts: a program the extension starts with
`chrome.runtime.connectNative` or `sendNativeMessage`, found through a
manifest the app installs for each browser it supports. 1Password and
Bitwarden install theirs for Google Chrome, in
`~/Library/Application Support/Google/Chrome/NativeMessagingHosts`, not
for an app built on CEF. Chromium in CEF looks only in
`NativeMessagingHosts` in the root cache directory and in
`/Library/Application Support/Chromium/NativeMessagingHosts`.

`nativeMessagingHostDirectories` lists more directories to take hosts
from. The `.chrome` preset lists
`CefRuntime.Configuration.chromeNativeMessagingHostDirectories`: Google
Chrome's (stable, Beta, Dev and Canary) and Chromium's in the user's
Application Support, and Google Chrome's in `/Library/Google/Chrome`. The
other presets list none.

```swift
var configuration = CefRuntime.Configuration.chrome
// Chrome's and Chromium's hosts, then Brave's.
configuration.nativeMessagingHostDirectories = CefRuntime.Configuration.chromeNativeMessagingHostDirectories + [
    FileManager.default.homeDirectoryForCurrentUser
        .appendingPathComponent("Library/Application Support/BraveSoftware/Brave-Browser/NativeMessagingHosts"),
]
```

At start-up CefKit links each manifest in those directories into the root
cache directory's `NativeMessagingHosts`, where Chromium reads it when an
extension connects. The first directory with a host's name wins it, and a
manifest the app writes there itself wins over all of them and is never
replaced. Links to hosts that are gone are removed. A host installed while
the app runs is found at its next start.

A host answers only the extensions its manifest's `allowed_origins` names,
by identifier, so an extension installed from the Chrome Web Store reaches
its own app's host, as in Chrome. The host also learns the calling
extension and can check the app that started it: the desktop app decides
whether to trust a browser it does not know, and some ask the user or
refuse until it is added to their list of browsers. SelfTest's
`extensions` group checks the lookup, `connectNative`, `sendNativeMessage`
and an uninstalled host with an echo host of its own; it does not run any
password manager's host.

### Trust

Extensions are third-party code with the reach Chrome gives them, inside
the app's browser processes: they read and change the pages they have
access to, see requests, and can talk to native messaging hosts the user
installed (in the root cache directory and the directories
`nativeMessagingHostDirectories` lists). The app controls which can be
installed: CefChromium's `installed` and `uninstall`, the configuration's
list, and, on managed Macs, the administrator's policies. Extensions run
in incognito only when allowed, one by one; they never run in Alloy-style
pages' own interface, but their content scripts and network rules do
apply to pages there.

## Extensions: Chromium's own, through `chrome://extensions`

Measured with SelfTest's survey (`SELFTEST_ONLY=extensions
SELFTEST_EXTENSIONS_DUMP=1`, `=2` for Chrome's windows, `=3` for a
`CefWindow` with Chrome's toolbar, `SELFTEST_EXTENSIONS_STORE=<id>` for the
store) on CEF 156.0.28.

- **CEF's C API has none.** `cef_extension_t` and the extension handler went
  with the Alloy runtime's extension system; CEF 156's headers keep only
  `cef_browser_t::get_identifier` ("also used as the tabId for extension
  APIs", which in Chrome style it is not: tab ids are Chromium's session
  ids), the `IDC_*EXTENSIONS*` commands and `CEF_TASK_TYPE_EXTENSION`.
  Chrome style runs Chrome's whole extension system, so the route is the
  one Chrome's own `chrome://extensions` uses: `chrome.developerPrivate`
  and `chrome.management`, which Chromium grants that host. Nothing is
  read from pages, and nothing is injected into extensions.
- **Rejected:** the DevTools `Extensions` domain (`loadUnpacked`,
  `uninstall`, `triggerAction`) answers "Method not allowed": it needs
  `--remote-debugging-pipe` and `--enable-unsafe-extension-debugging`,
  which an app should not ship. Policies (`ExtensionInstallForcelist`,
  `ExtensionSettings`) set as recommended values (`defaults write`, what an
  app can write) show in `chrome://policy` as errors: Chromium accepts
  them only as mandatory, from an administrator. `"was_installed_by_default"`
  in an external extension's file does not keep Chromium from installing
  it disabled. `fetch` of `chrome://extension-icon` from the host is
  refused by its CSP; `developerPrivate` gives icons as `data:` URLs anyway.
- **What runs where.** Content scripts, `declarativeNetRequest` and
  `webRequest` apply in every page of the profile, Alloy-style views
  included; extension pages, popups and Chrome's extension UI need Chrome
  style. CEF makes each `CefWindow` its own Chromium `Browser` of type
  `popup` with one tab (`chrome.windows.getAll()` → `"popup"`), so
  `tabs.group`/`tabs.move` refuse its tabs ("Tabs can only be moved to and
  from normal windows") and `chrome.action.openPopup()` answers "Browser
  window has no toolbar", with or without Chrome's toolbar view; Chrome's
  extensions menu opens in such a window but its actions' popups do not.
  `openChromeWindow` windows are `normal`: there tabs, groups and popups
  are Chrome's. `tabs.create` and `windows.create` from a `CefWindow`'s
  extension page, and `runtime.openOptionsPage()`, open a Chrome window,
  which reaches `onChromeTab`.
- **Per-tab action state** (badge text and colour, title, icon an extension
  sets) lives in the browser process for Chromium's toolbar; no WebUI, Mojo
  interface or C API reads it, and asking the extension
  (`chrome.action.getBadgeText`) would mean running code in the extension's
  service worker through DevTools. `CefExtension.Action` is therefore the
  manifest's declared action.
- **The Web Store** works: its page has `chrome.webstorePrivate`, Add to
  Chrome shows Chromium's `ExtensionInstallDialogView` (a top-level widget
  window, not a child of the `CefWindow`), and accepting it installs. The
  banner "Switch to Chrome to install extensions" follows the brand in
  `navigator.userAgentData` (`Chromium`); no user-agent change is needed,
  so none is made.
- **Installing by identifier.** The external extensions directory is the
  one route that installs from the store without the user: Chromium
  downloads from `external_update_url` at start-up (about a minute in
  SelfTest), and installs an `external_crx` with no download. Both arrive
  disabled until accepted; enabling them once is the app's acceptance.
  An `--load-extension` directory loads in CEF 156 (Chrome's branded builds
  refuse the switch since Chrome 137), with no developer-mode warning in
  SelfTest's windows, in every profile.
- **Incognito.** Opening `chrome://extensions` in a `CefProfile.incognito()`
  ends the browser process, as `chrome://history` does, so the service
  host is the default profile's. An extension allowed in incognito did not
  run its content script in CEF's in-memory profile.
- **Uninstalling** confirms through Chromium's own bubble, whatever
  `showConfirmDialog` says, and wants a user activation; the library gives
  the host page one and accepts the bubble (see architecture.md). Not
  verified: that Chromium uninstalls an external extension whose file
  CefKit removed.

## Extensions

`CefExtensions` reads `developerPrivate.getExtensionsInfo()` (each
extension's state, location, permissions, commands, its icon as a `data:`
URL) and reads what that does not report, the toolbar action and the pages
an extension replaces, from the `manifest.json` in the directory Chromium
runs the extension from. Changes go through `management.setEnabled`,
`developerPrivate.updateExtensionConfiguration` (incognito, site access,
pinning), `reload`, `autoUpdate`, `updateProfileConfiguration` (developer
mode), `packDirectory` and `loadUnpacked`. Two need what a page's user
gives Chrome's own:

- `loadUnpacked` asks for the directory with a file dialog of the calling
  page. CEF routes a Chrome-style page's file dialogs to its client, so
  the service host's delegate answers it: `CefServiceHosts.fileDialogAnswers`
  holds the answer for the next dialog of a host.
- `management.uninstall` runs only with a user activation and always
  confirms, even with `showConfirmDialog: false` when the caller is not the
  extension itself. `CefServiceHosts.grantUserActivation(to:)` gives the
  host's page one (`Runtime.evaluate` with `userGesture`, the only DevTools
  call a service host makes), and `CefExtensions` presses the accepting
  button of Chromium's "Remove “…”?" bubble through accessibility; the app
  asks the user first.

`developerPrivate.onItemStateChanged` reports changes while the host runs;
otherwise `CefExtensions` watches the profile's `Extensions` directory and
`Preferences` files and reads again, so it starts no host to stay current.

`CefRuntime.Configuration.extensions` is CefKit's: `.unpacked` adds
`--load-extension`, and `.webStore` and `.package` are written to
`<root>/External Extensions/<id>.json` before `cef_initialize`, Chromium's
user-level external extensions directory (`chrome::DIR_USER_EXTERNAL_EXTENSIONS`,
the user data directory's), read at start-up by every regular profile.
CefKit keeps a ledger of the files it wrote and removes its own when the
configuration drops them. Chromium installs these disabled (an external
install, `ExternalInstallManager`); `CefExtensions` enables each configured
one once and records it in the profile's `CefSwift Accepted Extensions`.

`CefRuntime.Configuration.nativeMessagingHostDirectories` is CefKit's too.
Chromium looks for a native messaging host's manifest in the user data
directory's `NativeMessagingHosts` (`chrome::DIR_USER_NATIVE_MESSAGING`) and
in `/Library/Application Support/Chromium/NativeMessagingHosts`
(`chrome::DIR_NATIVE_MESSAGING` for an unbranded build), and reads it when an
extension connects. Before `cef_initialize`, CefKit links every
`<name>.json` of the configured directories into the first of those,
leaving alone the files it did not make. Links, not copies, so that it
follows a host whose manifest changes. It keeps a ledger,
`.cefswift-hosts`, and removes its own links once their manifests are gone.

CefKit adds Chrome's toolbar to a `CefWindow` that asks for one: CEF
creates it with the browser view (`get_chrome_toolbar_type`) but leaves it
to the window to place (`cef_browser_view_t::get_chrome_toolbar`), hidden.
`CefWindow` adds it above the page once the view is in the window
(`on_window_changed`), shows it, and keeps its height in the box layout.
