Skip to content

Javascript Events och 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 Indikerar att detta för det första medgivandet från en besökare efter att den gjort sitt första val i rutan.
    • pageload Indikerar att detta är en efterkommande sidladdning där ett medgivande existerar.
    • update Indikerar att besökaren öppnat cookie-inställningar och ändrat sitt medgivande.

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('Medgivande finns för funktionella-cookies');
}
if (cookieTractor.consent.contains(cookieTractor.category.statistical)){
    console.log('Medgivande finns för statistik-cookies');
}
if (cookieTractor.consent.contains(cookieTractor.category.marketing)){
    console.log('Medgivande finns för marknadsförings-cookies');
}

More information about our SDK can be found on the page about JavaScript API.