Consent state API

An easy way to get the current cookie consent state.

When users have selected their preferences for consent, Openli will store a record of their consent choices.

In some cases, you might want to have a look at the given consent, so you can do (or not do) certain actions related to consent choices. We've made an easy way for you to get access to the cookie consent state by using a simple JavaScript command (which can be used in all scripts with access to the browser'swindow object):

window.legal.getCookieConsentState(); 
// Returns an object like:
// { analytics: true|false, marketing: true|false }

Use cases

Google Tag Manager

A common use case for this API call is with Google Tag Manager, e.g. making triggers fire only under certain conditions. For an in-depth example, check out Prevent triggers from firing in Google Tag Manager.

It is also possible to register standard JavaScript DOM event-listeners to enable your own code to respond when a user changes their consent preferences.

To ensure that your code is run as you intend, you must register listeners before your call tolegal.widget(...) for the cookie widget on your page.

Event name

Event description

legalmonster.cookie.analytics.accepted

Triggered whenever a user gives consent to the analytics category. Can occur more than once.

legalmonster.cookie.analytics.rejected

Triggered whenever a user rejects consent to the analytics category. Can occur more than once.

legalmonster.cookie.marketing.accepted

Triggered whenever a user gives consent to the marketing category. Can occur more than once.

legalmonster.cookie.marketing.rejected

Triggered whenever a user rejects consent to the marketing category. Can occur more than once.

Here is an example of using one of these events to invoke some custom code:

function handleAnalyticsAccepted() {
    console.log("User accepted analytics.");
    // Take any other action you want to.
}

window.addEventListener(
    // The event name to listen for.
    "legalmonster.cookie.analytics.accepted",
    // A reference to your custom function.
    handleAnalyticsAccepted,
    // Optional: remove the listener after the first instance of the event.
    { once: true }
);

Last updated