【问题标题】:Rust wasm : How to access HTMLDocument from web-sys?Rust wasm:如何从 web-sys 访问 HTMLDocument?
【发布时间】:2020-08-21 10:23:12
【问题描述】:

使用web-sys crate 我想从 HTMLDocument 访问cookie method

我想做这样的事情。这确实行不通。

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,它应该可以在像文档一样的窗口下访问。

它似乎不适用于以下内容:

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

documentation HTMLDocument 应该扩展 Document。

我知道 Rust 中没有继承,但是 我不能像这样从 Document 转换它:

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

into 函数相同。

这样可以访问 HTMLDocument 吗?

还有其他方法可以使用 web-sys 访问 cookie 吗?

是否正在进行中但现在无法正常工作?

【问题讨论】:

    标签: rust webassembly


    【解决方案1】:

    您需要的是一个动态演员表,这是通过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()

    【讨论】:

    • 感谢这项工作。 websys::HtmlDocument 有一个小错字,应该是web_sys::HtmlDocument
    • @Scott:确实,已修复。
    猜你喜欢
    • 2020-04-13
    • 2022-01-25
    • 1970-01-01
    • 2020-12-15
    • 2020-09-11
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    相关资源
    最近更新 更多