JavaScript Events and Functions
If you are not using attributes in the script tag, you can use JavaScript events to load scripts based on the visitor’s choice.
Listen for the CookieConsent event to run your code:
window.addEventListener('CookieConsent', function (event) {
console.log('CookieConsent:', event.detail);
});
This event includes details about the event; here is an example of the payload in event.detail:
{
added : ['marketing'],
removed : [],
current : ['undefined','necessary','marketing'],
trigger : 'initial'
}
Explanation of properties:
- added Contains categories where consent was added as a result of the event.
- removed Contains categories where consent was withdrawn as a result of the event.
- current Contains all consents present after the event.
- trigger Indicates what triggered the event; it can have the following values:
- initial Indicates that this is the first consent given by a visitor after making their initial choice in the dialogue.
- pageload Indicates that this is a subsequent page load where a consent already exists.
- update Indicates that the visitor has opened the cookie settings and changed their consent.
Here is an example of code that runs when consent for marketing cookies exists:
window.addEventListener('CookieConsent', function (event) {
if(!event.detail.current.includes('marketing'))
return;
console.log('We have marketing consent!');
});
If you want to listen for when a user withdraws consent:
window.addEventListener('CookieConsent', function (event) {
if(event.detail.trigger !== 'update')
return;
console.log('Added consents',event.detail.added);
console.log('Removed consents',event.detail.removed);
});
You can also check if consent has already been given with code:
if (cookieTractor.consent.contains(cookieTractor.category.functional)){
console.log('Consent exists for functional cookies');
}
if (cookieTractor.consent.contains(cookieTractor.category.statistical)){
console.log('Consent exists for statistical cookies');
}
if (cookieTractor.consent.contains(cookieTractor.category.marketing)){
console.log('Consent exists for marketing cookies');
}
More information about our SDK can be found on the page about JavaScript API.
Related information
Support
If you have questions about JavaScript events and functions, feel free to contact us at info@cookietractor.com.