Rust WASM 获取当前网页的URL

目录

Rust 写的 WASM 放在网页端使用,想在Rust代码中获悉当前网页的网址该如何实现?

首先要在 rust 项目的依赖文件中启用 web-sys 的 WindowDocument 特性,示例:

Cargo.toml

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"

[dependencies.web-sys]
version = "0.3.66"
features = ["Document", "Window"]

然后使用(类似JS的方式访问)浏览器API接口,示例:

src/lib.rs

use wasm_bindgen::prelude::*;

fn get_page_url() -> String {
    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let url = document.url().unwrap().to_string();

    url
}

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet() {
    alert(get_page_url().as_str());
}

网页端加载WASM库和调用函数的方式,示例:

index.html

<script type="module">
	import init, { greet } from './pkg/data_hash.js';
	// after wasm is loaded, call the greet function
	init().then(() => {
		greet();
	});
</script>