nw_sys/nw.rs
1//!
2//! Provides access to the global `nw` namespace and [`try_nw`] functions allowing
3//! to detect if the application is running inside of Node Webkit or in the browser.
4//!
5
6use js_sys::{Function, Object};
7use wasm_bindgen::prelude::*;
8
9#[wasm_bindgen]
10extern "C" {
11 /// Access to the global `nw` namespace.
12 ///
13 /// ⧉ [NWJS Documentation](https://docs.nwjs.io/en/latest/)
14 ///
15 #[wasm_bindgen (extends = Object, js_name = nw)]
16 #[derive(Debug, Clone)]
17 pub type Nw;
18
19 #[wasm_bindgen(js_namespace = console)]
20 pub fn error(s: &str);
21}
22
23/// Getter for the global `nw` namespace object
24///
25///
26/// ⧉ [NWJS Documentation]: https://docs.nwjs.io/en/latest/
27pub fn try_nw() -> Result<Nw, JsValue> {
28 let nw_opt = Function::new_no_args("return this.nw").call0(&JsValue::undefined());
29
30 match nw_opt {
31 Ok(value) => {
32 if value.is_undefined() {
33 error("NW not found");
34 Err(value)
35 } else {
36 let nw_ns: Nw = value.into();
37 Ok(nw_ns)
38 }
39 }
40 Err(err) => {
41 error(&format!("NW not found, error: {:?}", err));
42 Err(err)
43 }
44 }
45}
46
47/// Helper to test whether the application is running under
48/// Node Webkit or in a regular browser environment.
49pub fn is_nw() -> bool {
50 try_nw().is_ok()
51}