rust 如何从web-sys访问HTMLDocument?

bz4sfanl  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(173)

使用web-sys crate,我想从HTMLDocument访问cookie方法。
我想做这样的事情,这确实行不通。

let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let cookie = document.cookie().unwrap();
//no method named `cookie` found for type `web_sys::features::gen_Document::Document` in the current scope

我需要访问HTMLDocument结构,而不是Document结构。
已启用功能的Cargo.toml。

~snip~
[dependencies.web-sys]
version = "0.3.4"
features = [
  "WebSocket",
  'Window',
  'Document',
  'HtmlDocument',
]

根据API,它应该可以在Window下访问,如Document
它似乎不适用于以下内容:

let html_document = window.html_document().unwrap();

HTMLDocument应该从documentation扩展到Document
我知道Rust中没有继承,但我不能像这样从Document转换它:

let html_document = web_sys::HtmlDocument::from(document);

这与into函数相同。
是否可以通过这种方式访问HTMLDocument
是否有其他方法可以使用web-sys访问cookie?
是不是正在进行中的工作现在不起作用了?

4nkexdtk

4nkexdtk1#

您需要的是一个 * 动态强制转换 *,它是使用wasm_bindgen::JsCast::dyn_into()完成的:

use wasm_bindgen::JsCast;

let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let html_document = document.dyn_into::<web_sys::HtmlDocument>().unwrap();
let cookie = html_document.cookie().unwrap();

还有一个变量wasm_bindgen::JsCast::dyn_ref(),它不使用原始对象。

相关问题