Skip to content

Instantly share code, notes, and snippets.

@ilyazub
Last active November 28, 2022 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilyazub/47235be0dbcb550d80408c229c54a416 to your computer and use it in GitHub Desktop.
Save ilyazub/47235be0dbcb550d80408c229c54a416 to your computer and use it in GitHub Desktop.
Render HTML with loaded JavaScript to stdout using Wry

Render HTML and print it to stdout after window.onload using wry

Initially posted at tauri-apps/wry#761 (reply in thread).

Steps

Save code from main.rs somewhere

Compile script

cargo build -r

Execute script

It takes about one second to render HTML with JS and return back the HTML string. Only started checking the profiler.

time ./target/release/wry_test_render
0.17user 0.07system 0:00.81elapsed 30%CPU (0avgtext+0avgdata 80388maxresident)k
0inputs+0outputs (172major+7466minor)pagefaults 0swaps

Double-check that source and resulting files are different

du -sh source.html rendered.html 
688K	source.html
752K	rendered.html
[package]
name = "wry_render_html_to_stdout"
authors = [ "Illia <ilya@serpapi.com>" ]
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
wry = "0.22.5"
[profile.release]
debug = 1
use std::fs::{canonicalize, read_to_string};
use wry::{
application::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
},
webview::WebViewBuilder,
};
const RETURN_OUTER_HTML: &str = r#"
window.onload = function() {
let html = document.documentElement.outerHTML;
window.ipc.postMessage(html);
}
"#;
fn main() -> wry::Result<()> {
enum UserEvents {
CloseWindow,
}
let event_loop = EventLoop::<UserEvents>::with_user_event();
let window = WindowBuilder::new()
.with_title("Render HTML to string")
.with_visible(false)
.build(&event_loop)?;
let html = read_to_string(canonicalize("./MY_HTML_FILE.html")?)?;
let proxy = event_loop.create_proxy();
let handler = move |_window: &Window, html: String| {
println!("{}", &html);
let _ = proxy.send_event(UserEvents::CloseWindow);
};
let _webview = WebViewBuilder::new(window)?
.with_html(&html)?
.with_initialization_script(RETURN_OUTER_HTML)
.with_ipc_handler(handler)
.build()?;
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;
match event {
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
}
| Event::UserEvent(UserEvents::CloseWindow) => {
*control_flow = ControlFlow::Exit
}
_ => (),
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment