loadWebSdk function

Future<void> loadWebSdk({
  1. HTMLElement? target,
  2. String trustedTypePolicyName = _defaultTrustedPolicyName,
  3. String? nonce = _undefined,
})

Loads the GIS SDK for web, using Trusted Types API when available.

This attempts to use Trusted Types when available, and creates a new policy with the given trustedTypePolicyName.

By default, the script will attempt to copy the nonce attribute from other scripts in the page. The nonce parameter will be used when passed, and not-null. When nonce parameter is explicitly null, no nonce attribute is applied to the script.

Implementation

Future<void> loadWebSdk({
  web.HTMLElement? target,
  String trustedTypePolicyName = _defaultTrustedPolicyName,
  String? nonce = _undefined,
}) {
  final Completer<void> completer = Completer<void>();
  onGoogleLibraryLoad = () => completer.complete();

  // If TrustedTypes are available, prepare a trusted URL.
  web.TrustedScriptURL? trustedUrl;
  if (web.window.nullableTrustedTypes != null) {
    web.console.debug(
      'TrustedTypes available. Creating policy: $trustedTypePolicyName'.toJS,
    );
    try {
      final web.TrustedTypePolicy policy = web.window.trustedTypes.createPolicy(
          trustedTypePolicyName,
          web.TrustedTypePolicyOptions(
            createScriptURL: ((JSString url) => _url).toJS,
          ));
      trustedUrl = policy.createScriptURLNoArgs(_url);
    } catch (e) {
      throw TrustedTypesException(e.toString());
    }
  }

  final web.HTMLScriptElement script = web.HTMLScriptElement()
    ..async = true
    ..defer = true;
  if (trustedUrl != null) {
    script.trustedSrc = trustedUrl;
  } else {
    script.src = _url;
  }

  if (_getNonce(suppliedNonce: nonce) case final String nonce?) {
    script.nonce = nonce;
  }

  (target ?? web.document.head!).appendChild(script);

  return completer.future;
}