Skip to main content

Cef

Struct Cef 

Source
pub struct Cef { /* private fields */ }
Expand description

Selects and configures the CEF runtime.

Pass it to tauri::Builder::runtime to run the application with CEF:

tauri::Builder::default().runtime(
  tauri_runtime_cef::Cef::default().command_line_arg("disable-gpu", None::<String>),
);

Implementations§

Source§

impl Cef

Source

pub fn on_window_event<F>(self, handler: F) -> Self
where F: Fn(&str, &dyn ActiveEventLoop, Arc<dyn Window>, &WinitWindowEvent) + Send + Sync + 'static,

Observes native input, resize and redraw events without replacing Tauri’s handling.

Runs before Tauri handles the event. Offscreen embedders forward input, focus and IME to CEF and present their own GPU surface here. Release GPU resources and retained native window references on Destroyed. Registering this callback does not enable OSR or forward input automatically.

Source

pub fn with_settings<F>(self, callback: F) -> Self
where F: FnOnce(&mut Settings) + Send + Sync + 'static,

Sets a callback to customize the settings passed to cef::initialize.

If called more than once, only the last callback is used.

Source

pub fn command_line_arg<K: Into<String>, V: Into<String>>( self, key: K, value: Option<V>, ) -> Self

Appends one command line argument passed to CEF.

The argument is applied to the browser process only. CEF warns that modifying the command line of a non-browser process “may result in undefined behavior including crashes”, and Chromium already forwards to each child process the switches it needs.

Source

pub fn command_line_args<K: Into<String>, V: Into<String>>( self, args: impl IntoIterator<Item = (K, Option<V>)>, ) -> Self

Appends a list of command line arguments passed to CEF.

Like Self::command_line_arg, these are applied to the browser process only.

Appends a list of deep link schemes detected by CEF’s on_already_running_app_relaunch hook.

Deep links defined by the core deep-link plugin on the Tauri configuration are automatically added.

Source

pub fn root_cache_path<P: AsRef<Path>>(self, path: P) -> Self

Directory used for CEF disk cache (Settings::cache_path): Chromium’s user data directory, holding Local State, every profile and the caches.

If unspecified, defaults to {user cache}/{app identifier}/cef.

Give CEF a directory of its own. The runtime keeps a Last Version file in it naming the Chromium that ran last, and DowngradePolicy::ResetProfile moves the whole directory aside when a newer Chromium milestone last used it — see Self::downgrade.

Source

pub fn downgrade(self, policy: DowngradePolicy) -> Self

What to do with the profile on disk when a newer Chromium milestone last used it, which is what a release rolled back to an older CEF finds.

Defaults to DowngradePolicy::KeepProfile: the profile is opened as is and a warning is logged, as Chrome does. DowngradePolicy::ResetProfile moves it aside and starts clean instead. See DowngradePolicy for what each one costs.

Source

pub fn cef_api_version(self, version: i32) -> Self

CEF API version this process declares (cef_api_hash), defaulting to cef::sys::CEF_API_VERSION_LAST. Child processes declare the same one.

The Rust bindings are compiled for CEF_API_VERSION_LAST whatever is declared here. Declaring another version is only sound if the API the application uses is the same in both.

Source

pub fn secret_storage(self, storage: SecretStorage) -> Self

Which key Chromium uses to encrypt cookies and saved passwords at rest.

Defaults to SecretStorage::Auto: development builds skip the OS secret store — the macOS keychain prompt is replaced by a mock keychain, and Linux skips the D-Bus secret portal, libsecret and KWallet — while release builds use it. Windows keeps using DPAPI throughout.

Nothing but cookies and saved passwords is affected. The mock keychain and the Linux basic store encrypt with a hard-coded, publicly known constant, so reach for SecretStorage::Mock only when a release build has to run where no secret store exists at all. Switching between key sources makes previously stored cookies unreadable. See SecretStorage for the details.

Source

pub fn profile_preference<K: Into<String>>(self, name: K, enabled: bool) -> Self

Sets one boolean Chromium profile preference on every webview’s request context.

Applied after the runtime’s own defaults, so it can turn a preference the runtime disabled back on as well as turn something else off. Calling it twice for the same preference keeps the last value.

The runtime disables a handful of Chrome browser features that have no place in an application webview — the “Save password?” and address and credit-card bubbles (credentials_enable_service, profile.password_manager_leak_detection, autofill.profile_enabled, autofill.credit_card_enabled), the translate bubble (translate.enabled), and two background requests to Google (alternate_error_pages.enabled, search.suggest_enabled). An application that wants one of them names it here.

Safe Browsing (safebrowsing.enabled) is left on by the runtime; an application whose webview only ever loads its own content can switch it off here.

Preference names are Chromium’s own, and which ones a given Chrome build registers as writable varies. A preference this build refuses is logged at debug and skipped.

Cef::default()
  .profile_preference("credentials_enable_service", true)
  .profile_preference("safebrowsing.enabled", false);
Source

pub fn profile_preference_value<K: Into<String>, V: Into<Value>>( self, name: K, value: V, ) -> Self

Sets one Chromium profile preference of any type on every webview’s request context.

Self::profile_preference covers the common boolean case; this one takes the integers, strings, lists and dictionaries the rest of Chromium’s preferences are made of. The value must have the type Chromium registered the preference with — a string where an integer belongs is refused and logged at debug.

Preferences worth knowing about, beyond the ones with a typed option of their own:

PreferenceTypeWhat it does
printing.enabledboolwhether window.print() opens Chrome’s print preview
download.default_directorystringwhere downloads land
download.prompt_for_downloadboolwhether every download asks first
enable_do_not_trackboolsends the DNT header
enable_referrersboolsends Referer at all
dns_over_https.modestringoff, automatic or secure
dns_over_https.templatesstringspace-delimited DoH server templates
profile.cookie_controls_modeint1 blocks third-party cookies
hardware.audio_capture_enabledboola hard kill switch for the microphone
hardware.video_capture_enabledboolthe same for the camera
Cef::default()
  .profile_preference_value("dns_over_https.mode", "secure")
  .profile_preference_value("profile.cookie_controls_mode", 1);
Source

pub fn global_preference<K: Into<String>, V: Into<Value>>( self, name: K, value: V, ) -> Self

Sets one preference in Chromium’s local state, the store shared by every profile.

Most preferences belong to a profile and are set with Self::profile_preference_value; a handful — devtools.remote_debugging.allowed and hardware_acceleration_mode.enabled among them — live here instead. Applied once the CEF context is initialized.

Source

pub fn default_content_setting( self, content_type: ContentSettingTypes, value: ContentSettingValues, ) -> Self

Sets the default value of one Chromium content setting for every origin.

A content setting is the stored answer behind a permission: with a default of ContentSettingValues::BLOCK a page cannot ask at all, and with ALLOW it is granted without a prompt. That makes this the application-wide policy that WebviewAttributes::on_permission_request is not: the handler answers one request at a time, this decides what can be requested.

Applied to every webview’s request context after it initializes, and stored in the profile, so it also governs the origins the user has already answered for.

Chromium refuses to write a default onto an off-the-record profile, so this has no effect on a webview built with WebviewAttributes::incognito. Such a webview keeps Chromium’s own defaults, and WebviewAttributes::on_permission_request is the way to answer for it.

use tauri_runtime_cef::cef::{ContentSettingTypes, ContentSettingValues};

Cef::default()
  // An application webview has no business asking for these.
  .default_content_setting(ContentSettingTypes::NOTIFICATIONS, ContentSettingValues::BLOCK)
  .default_content_setting(ContentSettingTypes::GEOLOCATION, ContentSettingValues::BLOCK)
  // Device access a desktop application rarely wants a page to reach.
  .default_content_setting(ContentSettingTypes::USB_GUARD, ContentSettingValues::BLOCK)
  .default_content_setting(ContentSettingTypes::SERIAL_GUARD, ContentSettingValues::BLOCK)
  .default_content_setting(ContentSettingTypes::HID_GUARD, ContentSettingValues::BLOCK);

Blocking JAVASCRIPT_JIT is worth knowing about separately: it runs V8 without its optimizing compilers, which removes the largest single source of exploitable memory bugs in a renderer at a real cost in JavaScript performance. It is the same lever as Chrome’s DefaultJavaScriptJitSetting policy.

Source

pub fn allow_chromium_command_line_args(self, allow: bool) -> Self

Lets Chromium read switches off the process command line in release builds.

Release builds ignore them by default (Settings::command_line_args_disabled), because otherwise anyone who can start the shipped executable can also start it with --remote-debugging-port and drive the app over the DevTools protocol, or with --disable-web-security, --proxy-server, --host-resolver-rules or --ssl-key-log-file — Chromium honours every one of them. Development builds (tauri::is_dev()) always keep the command line enabled.

Enable this only if the application genuinely needs users to pass Chromium switches. It is not a complete lockdown either way: the network service reads the SSLKEYLOGFILE environment variable regardless of this setting.

Switches configured through Self::command_line_arg are unaffected, because CEF clears Chromium’s command line before applying its own settings and before calling on_before_command_line_processing. Tauri’s own CLI parsing and its cold-start deep link handling read std::env::args(), which Chromium never touches, and are unaffected too. Deep links delivered to an already running instance do go through Chromium’s process singleton, so the runtime restores the deep link URL onto the cleared command line to keep them working.

Source

pub fn log_file<P: AsRef<Path>>(self, path: P) -> Self

File Chromium and CEF write their log to (Settings::log_file).

Defaults to cef.log inside the cache directory (see Self::root_cache_path). With no log file configured, CEF writes a debug.log into the main executable directory on Windows and Linux, which for an installed application is often not even writable.

The default also overrides the macOS convention of ~/Library/Logs/<app name>_debug.log; pass that path explicitly to keep it.

Source

pub fn log_severity(self, severity: LogSeverity) -> Self

Lowest severity Chromium and CEF write to the log file (Settings::log_severity).

Defaults to cef::LogSeverity::WARNING in release builds — CEF’s own default is INFO, which is chatty enough to grow the log file of a long-running application — and to cef::LogSeverity::DEFAULT in development builds (tauri::is_dev()), where the informational messages are usually what you want.

cef::LogSeverity::DISABLE does not turn logging off entirely: CEF maps it to a FATAL-only minimum level, so nothing is written to the log file but FATAL messages still go to stderr.

Source

pub fn locale<S: Into<String>>(self, locale: S) -> Self

Locale Chromium loads its own localized resources for (Settings::locale), as an ISO language code such as en-US or pt-BR.

Leave unset — the default — unless you know the matching pak file ships with the application. Tauri’s bundler packages only the en-US locale pak, so naming any other locale leaves Chromium unable to load the localized strings it uses for its own UI (context menus, error pages, form controls). This does not affect the application’s own content, nor which languages a website is asked for — that is Self::accept_language_list.

Source

pub fn accept_language_list<S: Into<String>>(self, languages: S) -> Self

Comma-delimited list of languages sent as the Accept-Language header and reported through navigator.language (Settings::accept_language_list), for example en-US,en,pt-BR.

Defaults to CEF’s own value, which is derived from Self::locale.

Source

pub fn sandbox(self, policy: SandboxPolicy) -> Self

What to do with Chromium’s process sandbox.

Defaults to SandboxPolicy::Auto, which keeps the sandbox except when the application runs from an AppImage on a Linux or BSD system that offers no way to sandbox at all — AppImages cannot ship the setuid chrome-sandbox helper the deb and rpm bundlers install, and distributions such as Ubuntu 23.10 and later restrict the unprivileged user namespaces Chromium would otherwise fall back to. Without the escape hatch Chromium aborts at startup with “No usable sandbox!”.

See SandboxPolicy for the other variants.

Source

pub fn disable_features<S: Into<String>>( self, features: impl IntoIterator<Item = S>, ) -> Self

Adds names to Chromium’s --disable-features list, keeping what is already there.

Use this rather than command_line_arg("disable-features", ...). Chromium stores a switch by name and the last value appended replaces the previous one, so a raw --disable-features does not add to the list — it becomes the list, dropping the entries CEF put there to keep Chrome from crashing at startup and to keep renderers from being killed on the runtime’s own requests.

Source

pub fn enable_features<S: Into<String>>( self, features: impl IntoIterator<Item = S>, ) -> Self

Adds names to Chromium’s --enable-features list, keeping what is already there.

See Self::disable_features for why the raw switch is the wrong tool.

Source

pub fn debug_environment(self, policy: DebugEnvironment) -> Self

Whether Chromium and CEF may read their diagnostic environment variables.

Chromium honours SSLKEYLOGFILE — which writes the keys that decrypt every TLS session the application makes — and CEF honours three variables that redirect crash reports, whose minidumps carry process memory. Neither group is reachable through a CEF setting, so each is refused where Chromium reads it: the key log through an empty --ssl-key-log-file, which Chromium consults ahead of the variable, and the crash overrides by taking them out of the environment before CEF starts.

Defaults to DebugEnvironment::Auto: honoured in development builds (tauri::is_dev()), refused in release builds.

Source

pub fn remote_debugging(self, remote_debugging: RemoteDebugging) -> Self

Whether Chromium’s DevTools protocol server runs, and how it is reached.

Defaults to RemoteDebugging::Disabled, which additionally pins Chromium’s devtools.remote_debugging.allowed preference off so the server is refused even if the switch reaches Chromium another way.

See RemoteDebugging for what each transport exposes.

Source

pub fn devtools(self, policy: DevToolsPolicy) -> Self

Whether this application may open a DevTools window at all.

Defaults to DevToolsPolicy::Auto, which refuses them in a build that could not open them anyway. See DevToolsPolicy for how this combines with the per-webview WebviewAttributes::devtools, and for why it leaves the DevTools protocol alone.

Source

pub fn certificate_errors(self, policy: CertificateErrorPolicy) -> Self

What to do about a navigation to a server whose TLS certificate does not validate.

Defaults to CertificateErrorPolicy::ChromeInterstitial, which is Chromium’s own behaviour: an interstitial the user can click through.

Source

pub fn proxy(self, proxy: ProxyConfig) -> Self

How Chromium resolves the proxy for every request.

Defaults to ProxyConfig::System, Chromium’s own behaviour.

Source

pub fn autoplay(self, policy: AutoplayPolicy) -> Self

When a page may start playing media on its own.

Source

pub fn webrtc_ip_handling(self, policy: WebRtcIpHandling) -> Self

Which local network interfaces WebRTC may reveal to a page.

Source

pub fn spell_checking(self, enabled: bool) -> Self

Whether Chromium’s spell checker runs.

On by default. The first use of a language downloads its dictionary from Google’s redirector.gvt1.com, which is the only reason an application that never shows an editable field might want it off. The remote spelling service, which would send typed text to Google, is off either way.

Source

pub fn safe_browsing(self, enabled: bool) -> Self

Whether Chromium’s Safe Browsing protection runs.

On by default, and worth keeping on for any webview that loads content the application does not control — an OAuth or SSO flow, an embedded third-party page. Standard protection checks a locally stored hash-prefix database rather than calling Google per navigation, and keeping it updated is the periodic request an application that only ever loads its own content might want to be rid of.

Source

pub fn component_updates(self, enabled: bool) -> Self

Whether Chromium’s component updater runs.

On by default, and it is the mechanism that keeps the certificate revocation set, the Certificate Transparency log list and the download file-type policies current — security data that goes stale. Turn it off only for a deployment that has no route to update.googleapis.com at all.

Source

pub fn user_agent<S: Into<String>>(self, user_agent: S) -> Self

Value returned as the User-Agent header and navigator.userAgent, for every webview in the process (CefSettings.user_agent).

Replacing the whole string drops the Chrome and platform tokens sites branch on, so prefer Self::user_agent_product, which keeps them. A single webview can override this through WebviewAttributes::user_agent.

Source

pub fn user_agent_product<S: Into<String>>(self, product: S) -> Self

Product token spliced into Chromium’s own User-Agent string, such as MyApp/1.2.0 (CefSettings.user_agent_product).

Ignored when Self::user_agent is set.

Source

pub fn persist_session_cookies(self, persist: bool) -> Self

Whether session cookies survive a restart (CefSettings.persist_session_cookies).

Off by default, matching a browser: a session cookie is dropped when the application exits. A desktop application that should keep users signed in across restarts wants this on, and should know that it writes those cookies to the cache directory, where they are only as protected as SecretStorage makes them.

Source

pub fn javascript_flags<S: Into<String>>(self, flags: S) -> Self

Flags passed to V8 (CefSettings.javascript_flags), such as --max-old-space-size=512.

Use this rather than command_line_arg("js-flags", ...), which replaces the value CEF derives from this setting instead of adding to it.

Source

pub fn chrome_policy_id<S: Into<String>>(self, policy_id: S) -> Self

Enables Chrome policy management, reading policies from the platform location this identifier names (CefSettings.chrome_policy_id).

The identifier is a registry key on Windows (SOFTWARE\\Policies\\Vendor\\App), a bundle identifier on macOS, and a directory on Linux (/etc/opt/vendor/app/policies). Set it for an application deployed by an IT department that has to configure it centrally; leave it unset otherwise, since it lets whoever controls that location change the application’s behaviour.

Source

pub fn log_items(self, items: LogItems) -> Self

Which fields CEF prepends to each line of the log file (CefSettings.log_items).

Defaults to CEF’s own choice.

Trait Implementations§

Source§

impl Debug for Cef

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Cef

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<T: UserEvent> From<Cef> for DynRuntimeInitAttrs<T>

Source§

fn from(attrs: Cef) -> Self

Converts to this type from the input type.
Source§

impl<T: UserEvent> RuntimeInitAttrs<T> for Cef

Source§

type Runtime = CefRuntime<T>

The runtime initialized with these attributes.
Source§

fn apply_config(&mut self, config: &Config) -> Result<()>

Applies attributes derived from the application configuration.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Cef

§

impl !UnwindSafe for Cef

§

impl Freeze for Cef

§

impl Send for Cef

§

impl Sync for Cef

§

impl Unpin for Cef

§

impl UnsafeUnpin for Cef

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T, U> ConvertParam<U> for T
where T: Into<U>,

Source§

fn into_raw(self) -> U

Source§

impl<T, U> ConvertReturnValue<U> for T
where T: Into<U>,

Source§

fn wrap_result(self) -> U

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more