global.go raw

   1  //go:build js && wasm
   2  
   3  package safejs
   4  
   5  import (
   6  	"fmt"
   7  	"syscall/js"
   8  )
   9  
  10  // Global returns the JavaScript global object, usually "window" or "global".
  11  func Global() Value {
  12  	return Safe(js.Global())
  13  }
  14  
  15  // MustGetGlobal fetches the given global, then verifies it is truthy. Panics on error or falsy values.
  16  // This is intended for simple global variable initialization, like preparing classes for later instantiation.
  17  //
  18  // For example:
  19  //
  20  //	var jsUint8Array = safejs.MustGetGlobal("Uint8Array")
  21  func MustGetGlobal(property string) Value {
  22  	value, err := getGlobal(property)
  23  	if err != nil {
  24  		panic(err)
  25  	}
  26  	return value
  27  }
  28  
  29  func getGlobal(property string) (Value, error) {
  30  	value, err := Global().Get(property)
  31  	if err != nil {
  32  		return Value{}, err
  33  	}
  34  	truthy, err := value.Truthy()
  35  	if err != nil {
  36  		return Value{}, err
  37  	}
  38  	if !truthy {
  39  		return Value{}, fmt.Errorf("global %q is not defined", property)
  40  	}
  41  	return value, nil
  42  }
  43