Skip to content

Commit

Permalink
feat(tauri-apps#474): implement callback for evaluating javascript in…
Browse files Browse the repository at this point in the history
… webview2
  • Loading branch information
Toromyx committed Jan 31, 2022
1 parent 80896d3 commit 69faacc
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 9 deletions.
66 changes: 66 additions & 0 deletions examples/evaluate_javascript.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use tao::event::{DeviceEvent, ElementState};

fn main() -> wry::Result<()> {
use wry::{
application::{
event::{Event, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
},
webview::WebViewBuilder,
};

let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("Hello World")
.build(&event_loop)?;
let webview = WebViewBuilder::new(window)?
.with_url("https://html5test.com")?
.build()?;

event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;

match event {
Event::NewEvents(StartCause::Init) => println!("Wry has started!"),
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
Event::DeviceEvent {
event: DeviceEvent::Key(raw),
..
} => {
if raw.state == ElementState::Released {
let _ = webview.evaluate_script(
format!(
"
window.__WRY_HEADS__ = Math.random() < 0.5;
window.alert(window.__WRY_HEADS__ ? 'Heads!' : 'Tails!');
window.__WRY_HEADS__;
"
)
.as_str(),
|result| {
let heads: bool = serde_json::from_str(result.as_str()).unwrap();
println!(
"{}",
match heads {
true => "Heads!",
false => "Tails!",
}
)
},
);
}
}
_ => {
let _ = webview.resize();
}
}
});
}
2 changes: 1 addition & 1 deletion examples/multi_window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ fn main() -> wry::Result<()> {
webviews
.get_mut(&id)
.unwrap()
.evaluate_script("openWindow()")
.evaluate_script("openWindow()", || ())
.unwrap();
trigger = false;
}
Expand Down
4 changes: 2 additions & 2 deletions src/webview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,8 +412,8 @@ impl WebView {
/// [`WebView`]. Use [`EventLoopProxy`] and a custom event to send scripts from other threads.
///
/// [`EventLoopProxy`]: crate::application::event_loop::EventLoopProxy
pub fn evaluate_script(&self, js: &str) -> Result<()> {
self.webview.eval(js)
pub fn evaluate_script(&self, js: &str, callback: impl FnOnce(String) -> () + 'static) -> Result<()> {
self.webview.eval(js, callback)
}

/// Launch print modal for the webview content.
Expand Down
15 changes: 9 additions & 6 deletions src/webview/webview2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ impl InnerWebView {
match super::rpc_proxy(&window, js, rpc_handler) {
Ok(result) => {
if let Some(script) = result {
Self::execute_script(&webview, script)?;
Self::execute_script(&webview, script, |_| ())?;
}
}
Err(e) => {
Expand Down Expand Up @@ -545,21 +545,24 @@ impl InnerWebView {
)
}

fn execute_script(webview: &ICoreWebView2, js: String) -> windows::core::Result<()> {
fn execute_script(webview: &ICoreWebView2, js: String, callback: impl FnOnce(String) -> () + 'static) -> windows::core::Result<()> {
unsafe {
webview.ExecuteScript(
js,
ExecuteScriptCompletedHandler::create(Box::new(|_, _| (Ok(())))),
ExecuteScriptCompletedHandler::create(Box::new(|_, result_object_as_json| {
callback(result_object_as_json);
Ok(())
})),
)
}
}

pub fn print(&self) {
let _ = self.eval("window.print()");
let _ = self.eval("window.print()", |_| ());
}

pub fn eval(&self, js: &str) -> Result<()> {
Self::execute_script(&self.webview, js.to_string())
pub fn eval(&self, js: &str, callback: impl FnOnce(String) -> () + 'static) -> Result<()> {
Self::execute_script(&self.webview, js.to_string(), callback)
.map_err(|err| Error::WebView2Error(webview2_com::Error::WindowsError(err)))
}

Expand Down

0 comments on commit 69faacc

Please sign in to comment.