Reputation: 966
Recently I read the documentation of Rust and now I decided to play around with the web_sys API. I'm trying to use the Navigator::do_not_track
getter... well, to be more specific I would like to print the returning value. According to the documentation, that's the signature of the getter:
pub fn do_not_track(&self) -> String
If I understand this correctly, I should be able to use the format!
macro:
format!("{}", Navigator::do_not_track);
I have correctly imported the Navigator API, without any doubt. The error is:
error[E0277]: `for<'r> fn(&'r web_sys::features::gen_Navigator::Navigator) -> std::string::String {web_sys::features::gen_Navigator::Navigator::do_not_track}` doesn't implement `std::fmt::Display`
--> src/lib.rs:19:19
|
19 | format!("{}", Navigator::do_not_track);
| ^^^^^^^^^^^^^^^^^^^^^^^ `for<'r> fn(&'r web_sys::features::gen_Navigator::Navigator) -> std::string::String {web_sys::features::gen_Navigator::Navigator::do_not_track}` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `for<'r> fn(&'r web_sys::features::gen_Navigator::Navigator) -> std::string::String {web_sys::features::gen_Navigator::Navigator::do_not_track}`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required by `std::fmt::Display::fmt`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
And if I try to use web_sys::navigator
, I get
could not find "navigator" in "web_sys"
How do I access the web navigator API using web_sys
?
Upvotes: 2
Views: 1304
Reputation: 30052
Note that Navigator::do_not_track
is a method, which means that a value of type Navigator
needs to be retrieved first. One possible source of confusion was in not finding how to create it.
Most of the Web resources that you would find as global variables in a DOM-enabled JavaScript environment are available through the Window
resource. You need to:
web_sys = { version = "0.3", features = ["Navigator, Window"] }
Retrieve the global window via web_sys::window
, checking that it is available.
You can finally retrieve the intended resource through one of the available getter methods (window.navigator()
).
The code:
let window = web_sys::window().expect("Missing Window");
let navigator = window.navigator();
let do_not_track = navigator.do_not_track();
See also:
wasm-bindgen
guide, which also includes guidance on using web-sys
.Upvotes: 6