posthog-1.0.0-alpha5/modules/posthog_js/js/init.js
modules/posthog_js/js/init.js
/**
* @file
* Posthog JS initialization.
*/
(function (Drupal, drupalSettings) {
Drupal.behaviors.posthog_js_init = {
// @todo: Ensure that Drupal.attach is not too late! Eventually we should
// just call this without attach?
attach(context, settings) {
const posthogJsSettings = drupalSettings.posthog_js;
if (context !== document) {
// Only initialize on page load, not for AJAX content
// We MIGHT need to improve that in the future.
return;
}
if (window.posthog == null) {
// window.posthog should have been initialized here already
// by load.js from cdn or local library.
// Show a clear error, if it's still not available.
throw new Error(
`posthog_js: posthog-js SDK could not be loaded! You've chosen loading from: ${
posthogJsSettings.cdn ? 'CND' : 'posthog-js library'
}`,
);
}
if (!posthogJsSettings.api_key) {
throw new Error(
'posthog_js: Unable to initialize posthog! Missing API-Key!',
);
}
if (!posthogJsSettings.host) {
throw new Error(
'posthog_js: Unable to initialize posthog! Missing API-Host!',
);
}
// Initiate posthog with the provided settings:
window.posthog.init(posthogJsSettings.api_key, {
api_host: posthogJsSettings.host,
...posthogJsSettings.init_config_json,
});
// Expose posthog to the global scope:
Drupal.posthog = window.posthog;
// Identify the user if the feature is enabled and the distinct id is not
// null:
if (posthogJsSettings.distinct_id) {
// If he isn't anonymous, identify the user:
// Note, that even if we don't identify the user javascript-wise, we will
// still receive a cookie with a distinct id.
Drupal.posthog.identify(
posthogJsSettings.distinct_id,
posthogJsSettings.user_properties,
);
} else if (posthogJsSettings.identify_anonymous) {
Drupal.posthog.identify();
}
},
};
})(Drupal, drupalSettings);
