Skip to content

GTM Integration

Use this setup when the SDK is loaded by Google Tag Manager (GTM), not from npm runtime imports.

Browser global

When loaded by script, the SDK is exposed as:

window.SophiWebSDK.SophiWidget

Script URL (current)

Use this script URL in GTM-injected script element:

https://cdn.jsdelivr.net/npm/@usesophi/sophi-web-sdk@0.1.0-beta.8/dist/index.umd.js

Exact GTM trigger configuration

Tag

  • Tag Type: Custom HTML
  • Purpose: Load SDK only after functional consent is granted

Triggers

Attach the same Custom HTML tag to both triggers:

  1. Consent on Granted
  2. Page onload

This covers:

  • consent already granted before page load
  • consent granted during current session

Custom HTML behavior

The GTM tag should:

  1. Read and parse cookie_consent cookie as JSON
  2. Check parsed.functional === true
  3. If true, inject script URL (above) once
  4. On script load, dispatch:
  5. sophi:sdk_loaded
  6. sophi:init
<script>
  (function () {
    function getCookie(name) {
      var match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
      return match ? decodeURIComponent(match[2]) : null;
    }

    function hasFunctionalConsent() {
      try {
        var raw = getCookie("cookie_consent");
        if (!raw) return false;
        var parsed = JSON.parse(raw);
        return parsed && parsed.functional === true;
      } catch (e) {
        return false;
      }
    }

    if (!hasFunctionalConsent()) return;
    if (window.SophiWebSDK && window.SophiWebSDK.SophiWidget) return;

    var src =
      "https://cdn.jsdelivr.net/npm/@usesophi/sophi-web-sdk@0.1.0-beta.8/dist/index.umd.js";
    var script = document.createElement("script");
    script.src = src;
    script.async = true;

    script.onload = function () {
      window.dispatchEvent(new CustomEvent("sophi:sdk_loaded"));
      window.dispatchEvent(new CustomEvent("sophi:init"));
    };

    document.head.appendChild(script);
  })();
</script>

App-side wait flow

Initialize the widget only when:

  • functional consent exists
  • waitForSophiSDK(5000) resolves
  • readiness is confirmed by either:
  • sophi:init window event
  • window.SophiWebSDK.SophiWidget presence
const SophiWidgetClass = await waitForSophiSDK(5000);
const widget = new SophiWidgetClass();
await widget.init({
  apiKey: "YOUR_SOPHI_API_KEY",
  container: "#sophi-widget-container",
  userId,
  userName,
  environment: "production",
});

Warning

Keep configuration and event listeners in application code.
GTM should only handle consent-gated script loading.