Last active
October 31, 2023 10:05
-
-
Save sperand-io/4725e248a35d5005d68d810d8a8f7b29 to your computer and use it in GitHub Desktop.
Example of using analytics.js conditional loading with TrustArc Consent Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const [isConsentRequired, destinations] = await Promise.all([ | |
shouldRequireConsent(), | |
fetchDestinations([writeKey, ...otherWriteKeys]) | |
]) | |
const newDestinations = getNewDestinations( | |
destinations, | |
destinationPreferences | |
) | |
conditionallyLoadAnalytics({ | |
writeKey, | |
destinations, | |
destinationPreferences, | |
isConsentRequired | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function conditionallyLoadAnalytics({ | |
writeKey, | |
destinations, | |
destinationPreferences, | |
isConsentRequired, | |
shouldReload = true | |
}) { | |
const integrations = {All: false, 'Segment.io': true} | |
let isAnythingEnabled = false | |
if (!destinationPreferences) { | |
if (isConsentRequired) { | |
return | |
} | |
// Load a.js normally when consent isn't required and there's no preferences | |
if (!window.analytics.initialized) { | |
window.analytics.load(writeKey) | |
} | |
return | |
} | |
for (const destination of destinations) { | |
const isEnabled = Boolean(destinationPreferences[destination.id]) | |
if (isEnabled) { | |
isAnythingEnabled = true | |
} | |
integrations[destination.id] = isEnabled | |
} | |
// Reload the page if the trackers have already been initialised so that | |
// the user's new preferences can take affect | |
if (window.analytics.initialized) { | |
if (shouldReload) { | |
window.location.reload() | |
} | |
return | |
} | |
// Don't load a.js at all if nothing has been enabled | |
if (isAnythingEnabled) { | |
window.analytics.load(writeKey, {integrations}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment