wasm_bindgen_test/rt/
detect.rs

1//! Runtime detection of whether we're in node.js or a browser.
2
3use alloc::string::String;
4use wasm_bindgen::prelude::*;
5
6#[wasm_bindgen]
7extern "C" {
8    type This;
9    #[wasm_bindgen(method, getter, structural, js_name = self)]
10    fn self_(me: &This) -> Option<Scope>;
11
12    type Scope;
13    #[wasm_bindgen(method, getter, structural)]
14    fn constructor(me: &Scope) -> Constructor;
15
16    #[wasm_bindgen(method, getter, structural, js_name = Deno)]
17    fn deno(me: &Scope) -> Option<Deno>;
18
19    type Deno;
20
21    type Constructor;
22    #[wasm_bindgen(method, getter, structural)]
23    fn name(me: &Constructor) -> String;
24}
25
26/// Detecting the current JS scope
27pub fn detect() -> Runtime {
28    // Test whether we're in a browser/worker by seeing if the `self` property is
29    // defined on the global object and it is not equal to a WorkerScope, which should in turn
30    // only be true in browsers.
31    match js_sys::global().unchecked_into::<This>().self_() {
32        Some(scope) => match scope.constructor().name().as_str() {
33            "DedicatedWorkerGlobalScope"
34            | "SharedWorkerGlobalScope"
35            | "ServiceWorkerGlobalScope" => Runtime::Worker,
36            _ => match scope.deno() {
37                Some(_) => Runtime::Node,
38                _ => Runtime::Browser,
39            },
40        },
41        None => Runtime::Node,
42    }
43}
44
45/// Current runtime environment
46pub enum Runtime {
47    /// Current scope is a browser scope
48    Browser,
49    /// Current scope is a node scope
50    Node,
51    /// Current scope is a worker scope
52    Worker,
53}