Search code examples
rustwebassembly

How to access HTMLDocument from web-sys?


Using the web-sys crate, I want to access the cookie method from the HTMLDocument.

I want to do something like this. Indeed this does not work.

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

I would need to access the HTMLDocument struct not the Document struct.

Cargo.toml with features enabled.

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

According to the API, it should be accessible under Window, like Document.

It does not seem to be available with something like:

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

From the documentation, HTMLDocument should extend Document.

I know there is no inheritance in Rust but I cannot convert it from Document as such:

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

It is the same with the into function.

Is it possible to access HTMLDocument in such a way?

Is there another way to access the cookie using web-sys?

Is it something work-in-progress that is not working right now?


Solution

  • What you need is a dynamic cast, that is done with 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();
    

    There is also the variant wasm_bindgen::JsCast::dyn_ref() that does not consume the original object.