tauri::webview

Struct Webview

source
pub struct Webview<R: Runtime = Wry> { /* private fields */ }
Expand description

Webview.

Implementations§

source§

impl<R: Runtime> Webview<R>

Base webview functions.

source

pub fn builder<L: Into<String>>(label: L, url: WebviewUrl) -> WebviewBuilder<R>

Available on crate feature unstable only.

Initializes a webview builder with the given window label and URL to load on the webview.

Data URLs are only supported with the webview-data-url feature flag.

source

pub fn run_on_main_thread<F: FnOnce() + Send + 'static>( &self, f: F, ) -> Result<()>

Runs the given closure on the main thread.

source

pub fn label(&self) -> &str

The webview label.

source

pub fn on_webview_event<F: Fn(&WebviewEvent) + Send + 'static>(&self, f: F)

Registers a window event listener.

source§

impl<R: Runtime> Webview<R>

Webview APIs.

source

pub fn window(&self) -> Window<R>

The window that is hosting this webview.

source

pub fn window_ref(&self) -> MutexGuard<'_, Window<R>>

A reference to the window that is hosting this webview.

source

pub fn with_webview<F: FnOnce(PlatformWebview) + Send + 'static>( &self, f: F, ) -> Result<()>

Executes a closure, providing it with the webview handle that is specific to the current platform.

The closure is executed on the main thread.

§Examples
use tauri::Manager;

fn main() {
  tauri::Builder::default()
    .setup(|app| {
      let main_webview = app.get_webview("main").unwrap();
      main_webview.with_webview(|webview| {
        #[cfg(target_os = "linux")]
        {
          // see <https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/struct.WebView.html>
          // and <https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/trait.WebViewExt.html>
          use webkit2gtk::WebViewExt;
          webview.inner().set_zoom_level(4.);
        }

        #[cfg(windows)]
        unsafe {
          // see https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
          webview.controller().SetZoomFactor(4.).unwrap();
        }

        #[cfg(target_os = "macos")]
        unsafe {
          let view: &objc2_web_kit::WKWebView = &*webview.inner().cast();
          let controller: &objc2_web_kit::WKUserContentController = &*webview.controller().cast();
          let window: &objc2_app_kit::NSWindow = &*webview.ns_window().cast();

          view.setPageZoom(4.);
          controller.removeAllUserScripts();
          let bg_color = objc2_app_kit::NSColor::colorWithDeviceRed_green_blue_alpha(0.5, 0.2, 0.4, 1.);
          window.setBackgroundColor(Some(&bg_color));
        }

        #[cfg(target_os = "android")]
        {
          use jni::objects::JValue;
          webview.jni_handle().exec(|env, _, webview| {
            env.call_method(webview, "zoomBy", "(F)V", &[JValue::Float(4.)]).unwrap();
          })
        }
      });
      Ok(())
  });
}
source

pub fn url(&self) -> Result<Url>

Returns the current url of the webview.

source

pub fn navigate(&mut self, url: Url) -> Result<()>

Navigates the webview to the defined url.

source

pub fn on_message( self, request: InvokeRequest, responder: Box<OwnedInvokeResponder<R>>, )

Handles this window receiving an InvokeRequest.

source

pub fn eval(&self, js: &str) -> Result<()>

Evaluates JavaScript on this window.

source

pub fn open_devtools(&self)

Available on debug-assertions enabled or crate feature devtools only.

Opens the developer tools window (Web Inspector). The devtools is only enabled on debug builds or with the devtools feature flag.

§Platform-specific
  • macOS: Only supported on macOS 10.15+. This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
§Examples
use tauri::Manager;
tauri::Builder::default()
  .setup(|app| {
    #[cfg(debug_assertions)]
    app.get_webview("main").unwrap().open_devtools();
    Ok(())
  });
source

pub fn close_devtools(&self)

Available on debug-assertions enabled or crate feature devtools only.

Closes the developer tools window (Web Inspector). The devtools is only enabled on debug builds or with the devtools feature flag.

§Platform-specific
  • macOS: Only supported on macOS 10.15+. This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  • Windows: Unsupported.
§Examples
use tauri::Manager;
tauri::Builder::default()
  .setup(|app| {
    #[cfg(debug_assertions)]
    {
      let webview = app.get_webview("main").unwrap();
      webview.open_devtools();
      std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(10));
        webview.close_devtools();
      });
    }
    Ok(())
  });
source

pub fn is_devtools_open(&self) -> bool

Available on debug-assertions enabled or crate feature devtools only.

Checks if the developer tools window (Web Inspector) is opened. The devtools is only enabled on debug builds or with the devtools feature flag.

§Platform-specific
  • macOS: Only supported on macOS 10.15+. This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  • Windows: Unsupported.
§Examples
use tauri::Manager;
tauri::Builder::default()
  .setup(|app| {
    #[cfg(debug_assertions)]
    {
      let webview = app.get_webview("main").unwrap();
      if !webview.is_devtools_open() {
        webview.open_devtools();
      }
    }
    Ok(())
  });
source

pub fn set_zoom(&self, scale_factor: f64) -> Result<()>

Set the webview zoom level

§Platform-specific:
  • Android: Not supported.
  • macOS: available on macOS 11+ only.
  • iOS: available on iOS 14+ only.
source

pub fn clear_all_browsing_data(&self) -> Result<()>

Clear all browsing data for this webview.

Trait Implementations§

source§

impl<R: Runtime> AsRef<Webview<R>> for WebviewWindow<R>

source§

fn as_ref(&self) -> &Webview<R>

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<R: Runtime> Clone for Webview<R>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'de, R: Runtime> CommandArg<'de, R> for Webview<R>

source§

fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError>

Grabs the Webview from the CommandItem. This will never fail.

source§

impl<R: Runtime> Debug for Webview<R>

source§

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

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

impl<R: Runtime> Emitter<R> for Webview<R>

source§

fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> Result<()>

Emits an event to all targets.

§Examples
use tauri::Emitter;

#[tauri::command]
fn synchronize(webview: tauri::Webview) {
  // emits the synchronized event to all webviews
  webview.emit("synchronized", ());
}
source§

fn emit_to<I, S>(&self, target: I, event: &str, payload: S) -> Result<()>
where I: Into<EventTarget>, S: Serialize + Clone,

Emits an event to all targets matching the given target.

§Examples
use tauri::{Emitter, EventTarget};

#[tauri::command]
fn download(webview: tauri::Webview) {
  for i in 1..100 {
    std::thread::sleep(std::time::Duration::from_millis(150));
    // emit a download progress event to all listeners
    webview.emit_to(EventTarget::any(), "download-progress", i);
    // emit an event to listeners that used App::listen or AppHandle::listen
    webview.emit_to(EventTarget::app(), "download-progress", i);
    // emit an event to any webview/window/webviewWindow matching the given label
    webview.emit_to("updater", "download-progress", i); // similar to using EventTarget::labeled
    webview.emit_to(EventTarget::labeled("updater"), "download-progress", i);
    // emit an event to listeners that used WebviewWindow::listen
    webview.emit_to(EventTarget::webview_window("updater"), "download-progress", i);
  }
}
source§

fn emit_filter<S, F>(&self, event: &str, payload: S, filter: F) -> Result<()>
where S: Serialize + Clone, F: Fn(&EventTarget) -> bool,

Emits an event to all targets based on the given filter.

§Examples
use tauri::{Emitter, EventTarget};

#[tauri::command]
fn download(webview: tauri::Webview) {
  for i in 1..100 {
    std::thread::sleep(std::time::Duration::from_millis(150));
    // emit a download progress event to the updater window
    webview.emit_filter("download-progress", i, |t| match t {
      EventTarget::WebviewWindow { label } => label == "main",
      _ => false,
    });
  }
}
source§

impl<R: Runtime> FunctionArg for Webview<R>

source§

fn to_datatype(_: &mut TypeMap) -> Option<DataType>

Gets the type of an argument as a DataType. Read more
source§

impl<R: Runtime> Hash for Webview<R>

source§

fn hash<H: Hasher>(&self, state: &mut H)

Only use the Webview’s label to represent its hash.

1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<R: Runtime> Listener<R> for Webview<R>

source§

fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
where F: Fn(Event) + Send + 'static,

Listen to an event on this webview.

§Examples
use tauri::{Manager, Listener};

tauri::Builder::default()
  .setup(|app| {
    let webview = app.get_webview("main").unwrap();
    webview.listen("component-loaded", move |event| {
      println!("webview just loaded a component");
    });

    Ok(())
  });
source§

fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
where F: FnOnce(Event) + Send + 'static,

Listen to an event on this webview only once.

See Self::listen for more information.

source§

fn unlisten(&self, id: EventId)

Unlisten to an event on this webview.

§Examples
use tauri::{Manager, Listener};

tauri::Builder::default()
  .setup(|app| {
    let webview = app.get_webview("main").unwrap();
    let webview_ = webview.clone();
    let handler = webview.listen("component-loaded", move |event| {
      println!("webview just loaded a component");

      // we no longer need to listen to the event
      // we also could have used `webview.once` instead
      webview_.unlisten(event.id());
    });

    // stop listening to the event when you do not need it anymore
    webview.unlisten(handler);

    Ok(())
  });
source§

fn listen_any<F>(&self, event: impl Into<String>, handler: F) -> EventId
where F: Fn(Event) + Send + 'static,

Listen to an emitted event to any target. Read more
source§

fn once_any<F>(&self, event: impl Into<String>, handler: F) -> EventId
where F: FnOnce(Event) + Send + 'static,

Listens once to an emitted event to any target . Read more
source§

impl<R: Runtime> Manager<R> for Webview<R>

source§

fn resources_table(&self) -> MutexGuard<'_, ResourceTable>

Get a reference to the resources table of this manager.
source§

fn app_handle(&self) -> &AppHandle<R>

The application handle associated with this manager.
source§

fn config(&self) -> &Config

The Config the manager was created with.
source§

fn package_info(&self) -> &PackageInfo

The PackageInfo the manager was created with.
source§

fn get_window(&self, label: &str) -> Option<Window<R>>

Available on crate feature unstable only.
Fetch a single window from the manager.
source§

fn get_focused_window(&self) -> Option<Window<R>>

Available on crate feature unstable only.
Fetch the focused window. Returns None if there is not any focused window.
source§

fn windows(&self) -> HashMap<String, Window<R>>

Available on crate feature unstable only.
Fetch all managed windows.
source§

fn get_webview(&self, label: &str) -> Option<Webview<R>>

Available on crate feature unstable only.
Fetch a single webview from the manager.
source§

fn webviews(&self) -> HashMap<String, Webview<R>>

Available on crate feature unstable only.
Fetch all managed webviews.
source§

fn get_webview_window(&self, label: &str) -> Option<WebviewWindow<R>>

Fetch a single webview window from the manager.
source§

fn webview_windows(&self) -> HashMap<String, WebviewWindow<R>>

Fetch all managed webview windows.
source§

fn manage<T>(&self, state: T) -> bool
where T: Send + Sync + 'static,

Add state to the state managed by the application. Read more
source§

fn unmanage<T>(&self) -> Option<T>
where T: Send + Sync + 'static,

Removes the state managed by the application for T. Returns the state if it was actually removed.
source§

fn state<T>(&self) -> State<'_, T>
where T: Send + Sync + 'static,

Retrieves the managed state for the type T. Read more
source§

fn try_state<T>(&self) -> Option<State<'_, T>>
where T: Send + Sync + 'static,

Attempts to retrieve the managed state for the type T. Read more
source§

fn env(&self) -> Env

Gets the managed Env.
source§

fn asset_protocol_scope(&self) -> Scope

Gets the scope for the asset protocol.
source§

fn path(&self) -> &PathResolver<R>

The path resolver.
source§

fn add_capability(&self, capability: impl RuntimeCapability) -> Result<()>

Adds a capability to the app. Read more
source§

impl<R: Runtime> PartialEq for Webview<R>

source§

fn eq(&self, other: &Self) -> bool

Only use the Webview’s label to compare equality.

1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<R: Runtime> Eq for Webview<R>

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Same for T

source§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

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

source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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> UserEvent for T
where T: Debug + Clone + Send + 'static,