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:
Script URL (current)
Use this script URL in GTM-injected script element:
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:
- Consent on Granted
- Page onload
This covers:
- consent already granted before page load
- consent granted during current session
Custom HTML behavior
The GTM tag should:
- Read and parse
cookie_consentcookie as JSON - Check
parsed.functional === true - If true, inject script URL (above) once
- On script load, dispatch:
sophi:sdk_loadedsophi: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:initwindow eventwindow.SophiWebSDK.SophiWidgetpresence
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.