-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
53 lines (45 loc) · 1.28 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#![allow(unused_imports)]
extern crate wasm_bindgen;
extern crate web_sys;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::*;
#[wasm_bindgen]
pub fn greet() -> Result<String, JsValue> {
let origin = self_()?.origin();
Ok(format!("Hello from {}", origin))
}
trait WindowOrWorkerGlobalScope {
fn origin(&self) -> String;
}
impl WindowOrWorkerGlobalScope for Window {
fn origin(&self) -> String {
self.origin()
}
}
impl WindowOrWorkerGlobalScope for WorkerGlobalScope {
fn origin(&self) -> String {
self.origin()
}
}
//
// Can't use impl WindowOrWorkerGlobalScope as return type:
//
// fn self_() -> Result<impl WindowOrWorkerGlobalScope, JsValue> {
// let global = js_sys::global();
// if js_sys::eval("typeof WorkerGlobalScope !== 'undefined'")?.as_bool().unwrap() {
// Ok(global.dyn_into::<WorkerGlobalScope>()?)
// }
// else {
// Ok(global.dyn_into::<Window>()?)
// }
// }
fn self_() -> Result<Box<dyn WindowOrWorkerGlobalScope>, JsValue> {
let global = js_sys::global();
if js_sys::eval("typeof WorkerGlobalScope !== 'undefined'")?.as_bool().unwrap() {
Ok(Box::new(global.dyn_into::<WorkerGlobalScope>()?))
}
else {
Ok(Box::new(global.dyn_into::<Window>()?))
}
}