Magento 2 Cookie Consent v1.x Developer Guide

Welcome to the Developer Guide for the Magento 2 Cookie Consent Extension. Use the sample code and follow the step-by-step instructions to customize your Cookie Consent module.

How to Block Your Javascript Code Until a Customer Accepts Cookies

Option 1: Block JS using our javascript model:

Wrap your javascript code as in the example below:

requirejs(['prCookieRestriction'], function (prCookieRestriction) {
    'use strict';

    if (prCookieRestriction.isAllowedCategory('marketing')) {
        // your code goes here ...
    }
});

marketing” is the key of the Marketing category. The script will be executed if a customer allows the marketing category. Please, learn how to find a category key.

To find out more about the “prCookieRestriction” JS model, go to the following file:

Plumrocket/CookieConsent/view/frontend/web/js/model/restriction.js

Option 2: Block JS using “pr-cookie-consent” cookie:

If you are not able to use our js model, you can write your own solution based on the “pr-cookie-consent” cookie.

A “pr-cookie-consent” value is an array that includes categories allowed by a customer. The value is a URL encoded JSON string. For instance, if a customer allows cookies from the Statistics category, the consent will be recorded as [%22statistics%22] in the “pr-cookie-consent” array.

In the list below, you can see the examples of possible “pr-cookie-consent” cookie values (for illustrative purposes, the values are URL decoded):

  • [“statistics”] – a user allowed a Statistics category only.
  • [“preferences”,”statistics”]  – a user allowed Preferences and Statistics categories.
  • [“*”]  – a user allowed all cookies.
  • [] – a user declined all cookies or disabled all categories in a Cookie Settings Panel.

Please, note:

  • If a user has not allowed cookies yet, a “pr-cookie-consent” cookie is not created.
  • All but the essential categories are stored in the “pr-cookie-consent” cookie. Since the Essential categories are required and users are not able to decline them, these categories are not recorded in the cookie.

How to Integrate Google Analytics (GA) With Cookie Consent Extension

Built-in Google Analytics support

The module partially supports a built-in Magento Google Analytics module, namely:

  • Google Analytics executes when a user agrees to all cookie categories by clicking the “Allow All” button.
  • If you enable the Cookie Consent extension only for certain countries, Google Analytics executes after a customer allows cookies. For other countries, the Google Analytics code will work without restrictions.

How to enable Google Analytics for a particular cookie category

In order to block Google Analytics until a customer accepts cookies, you should use one of the following solutions:

Option 1: First, add your Google Analytics to Google Tag Manager. Then go to your Magento Admin Panel and configure Google Tag Manager in Cookie Consent Extension.

Option 2: Go to the Edit Cookie Category page in the backend and insert your Google Analytics tag in the Head Scripts field.

Option 3:

  • Step 1: create the following js file in your theme folder.
app/design/<Vendor>/<theme>/Magento_GoogleAnalytics/web/js/google-analytics.js
  • Step 2: Paste the following code into the created file.

In the example below, Google Analytics executes when a customer accepts the Statistics cookie category. If you want Google Analytics to execute when a customer accepts another cookie category, change the ‘statistics’ key in the following code to the relevant category key.

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/* jscs:disable */
/* eslint-disable */
define([
    'jquery',
    'prCookieRestriction',
], function ($, prCookieRestriction) {
    'use strict';

    /**
     * @param {Object} config
     */
    return function (config) {
        if (prCookieRestriction.isAllowedCategory('statistics')) {
            (function (i, s, o, g, r, a, m) {
                i.GoogleAnalyticsObject = r;
                i[r] = i[r] || function () {
                        (i[r].q = i[r].q || []).push(arguments)
                    }, i[r].l = 1 * new Date();
                a = s.createElement(o),
                    m = s.getElementsByTagName(o)[0];
                a.async = 1;
                a.src = g;
                m.parentNode.insertBefore(a, m)
            })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

            // Process page info
            ga('create', config.pageTrackingData.accountId, 'auto');

            if (config.pageTrackingData.isAnonymizedIpActive) {
                ga('set', 'anonymizeIp', true);
            }

            // Process orders data
            if (config.ordersTrackingData.hasOwnProperty('currency')) {
                ga('require', 'ec', 'ec.js');

                ga('set', 'currencyCode', config.ordersTrackingData.currency);

                // Collect product data for GA
                if (config.ordersTrackingData.products) {
                    $.each(config.ordersTrackingData.products, function (index, value) {
                        ga('ec:addProduct', value);
                    });
                }

                // Collect orders data for GA
                if (config.ordersTrackingData.orders) {
                    $.each(config.ordersTrackingData.orders, function (index, value) {
                        ga('ec:setAction', 'purchase', value);
                    });
                }

                ga('send', 'pageview');
            } else {
                // Process Data if not orders
                ga('send', 'pageview' + config.pageTrackingData.optPageUrl);
            }
        }
    }
});

How to Insert “Cookie Settings” Link Into a Custom Position

There are two ways to insert the Cookie Settings link into a custom position:

Option 1: Insert Cookie Settings button using provided CMS widget

Use Cookie Settings Button widget to insert Cookie Settings Link into a custom position. This widget will be displayed as a link or a button. When clicking on it, the Cookie Settings Panel opens.

  • You can use Widget Code and insert it into the CMS page or CMS block.
  • You can use the default Magento widget functionality to insert the widget.

Option 2: Create a custom Cookie Settings button using the CSS class

Add a ‘pr-open-cookie-settings‘ CSS class to any button or link. The Cookie Settings Panel opens when clicking on this element.

An example for a custom cookie settings button:

<button class="pr-open-cookie-settings">Cookie Settings</button>

An example for a custom cookie settings link:

<a href="#" class="pr-open-cookie-settings">Cookie Settings</a>

* Please note: the extension provides cookie settings link functionality to insert cookie settings link into footer links automatically.

Cookie Settings Panel

The following picture is an illustration of the Cookie Settings Panel displayed on the frontend.

Was this article helpful?