# Consent state API

## Retrieving the cookie consent state

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

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's`window` object):&#x20;

```javascript
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](https://docs.legalmonster.com/integrations/how-to-use-google-tag-manager-with-legal-monster/prevent-triggers-from-firing-in-gtm).

## Listening for consent-change events

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.

{% hint style="info" %}
To ensure that your code is run as you intend, you must register listeners **before your call to`legal.widget(...)` for the cookie widget** on your page.
{% endhint %}

| 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:

```javascript
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 }
);
```
