diff --git a/src/wasm32_bindgen.rs b/src/wasm32_bindgen.rs index c6eef5fd..86839a09 100644 --- a/src/wasm32_bindgen.rs +++ b/src/wasm32_bindgen.rs @@ -58,54 +58,38 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { } fn getrandom_init() -> Result { - // First up we need to detect if we're running in node.js or a - // browser. To do this we get ahold of the `this` object (in a bit - // of a roundabout fashion). - // - // Once we have `this` we look at its `self` property, which is - // only defined on the web (either a main window or web worker). - let this = Function::new("return this").call(&JsValue::undefined()); - assert!(this != JsValue::undefined()); - let this = This::from(this); - let is_browser = this.self_() != JsValue::undefined(); - - if !is_browser { - return Ok(RngSource::Node(node_require("crypto"))); - } + if let Ok(self_) = Global::get_self() { + // If `self` is defined then we're in a browser somehow (main window + // or web worker). Here we want to try to use + // `crypto.getRandomValues`, but if `crypto` isn't defined we assume + // we're in an older web browser and the OS RNG isn't available. + + let crypto = self_.crypto(); + if crypto.is_undefined() { + return Err(BINDGEN_CRYPTO_UNDEF); + } - // If `self` is defined then we're in a browser somehow (main window - // or web worker). Here we want to try to use - // `crypto.getRandomValues`, but if `crypto` isn't defined we assume - // we're in an older web browser and the OS RNG isn't available. - let crypto = this.crypto(); - if crypto.is_undefined() { - return Err(BINDGEN_CRYPTO_UNDEF); - } + // Test if `crypto.getRandomValues` is undefined as well + let crypto: BrowserCrypto = crypto.into(); + if crypto.get_random_values_fn().is_undefined() { + return Err(BINDGEN_GRV_UNDEF); + } - // Test if `crypto.getRandomValues` is undefined as well - let crypto: BrowserCrypto = crypto.into(); - if crypto.get_random_values_fn().is_undefined() { - return Err(BINDGEN_GRV_UNDEF); + return Ok(RngSource::Browser(crypto)); } - // Ok! `self.crypto.getRandomValues` is a defined value, so let's - // assume we can do browser crypto. - Ok(RngSource::Browser(crypto)) + return Ok(RngSource::Node(node_require("crypto"))); } #[wasm_bindgen] extern "C" { - type Function; - #[wasm_bindgen(constructor)] - fn new(s: &str) -> Function; - #[wasm_bindgen(method)] - fn call(this: &Function, self_: &JsValue) -> JsValue; - - type This; - #[wasm_bindgen(method, getter, structural, js_name = self)] - fn self_(me: &This) -> JsValue; + type Global; + #[wasm_bindgen(getter, catch, static_method_of = Global, js_class = self, js_name = self)] + fn get_self() -> Result; + + type Self_; #[wasm_bindgen(method, getter, structural)] - fn crypto(me: &This) -> JsValue; + fn crypto(me: &Self_) -> JsValue; #[derive(Clone, Debug)] type BrowserCrypto;