@unifygtm/intent-client
Version:
JavaScript client for interacting with the Unify Intent API in the browser.
38 lines (31 loc) • 1.12 kB
text/typescript
import { UnifyIntentClient } from '../client';
import { isIntentClient } from '../client/utils/helpers';
import { logUnifyError } from '../client/utils/logging';
/**
* Initializes the `UnifyIntentClient` and flushes pre-made method calls
* from the global context if there are any.
*/
export const initBrowser = function () {
// If not running in a browser environment, do nothing
if (typeof window === 'undefined') return;
// If the client has already been initialized, do nothing
if (isIntentClient(window.unify) || isIntentClient(window.unifyBrowser)) {
logUnifyError({
message:
'UnifyIntentClient already exists on window, a new one will not be created.',
});
return;
}
// Get public API key from the script tag
const scriptTag = document.getElementById('unifytag');
const writeKey =
scriptTag?.getAttribute('data-write-key') ??
scriptTag?.getAttribute('data-api-key');
if (!writeKey) return;
// Instantiate the Unify client and mount it
new UnifyIntentClient(writeKey, {
autoPage: true,
autoIdentify: true,
}).mount();
};
initBrowser();