Iubenda logo

Documentation

Table of Contents

How to integrate iubenda Cookie Solution with AMP

Collecting cookie consent on AMP pages requires some work. Luckily, iubenda can help. Let’s break down the steps you’ll need to take and see how to integrate our Cookie Solution with Google’s Accelerated Mobile Pages, including blocking cookies before user consent (and some useful tips for WordPress).

Step 1 – Create an HTML file

First of all, copy this HTML code and host it on your HTTPS site in an HTML file (be sure to edit the Cookie Solution configuration to reflect your own):

Please note that AMP is not compatible with per-category consent, Therefore, you may not specify perPurposeConsent: true in your configuration when using AMP.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="robots" content="noindex">
    <title>AMP Cookie Consent</title>
</head>

<body>
    <script type="text/javascript">
        var _iub = _iub || [];
        _iub.csConfiguration = {
            lang: 'en',
            siteId: 896537, // your own site ID
            cookiePolicyId: 8207462, // your own cookie policy ID

            // Your own Cookie Solution configuration
            enableCMP: true,
            askConsentIfCMPNotFound: true,
            perPurposeConsent: false, // forced to false since AMP does not support it
            // /Your own Cookie Solution configuration

            banner: {
                position: 'float-bottom-center', // Customize as you wish
                acceptButtonDisplay: true, // Recommended
                customizeButtonDisplay: true, // Recommended
                backgroundOverlay: true, // Mandatory since AMP requires loading the notice in a full-screen iframe and iframes cannot be click-through
                rejectButtonDisplay: true // Advisable
            },
            callback: { // Mandatory
                onPreferenceExpressed: function(preference) {
                    var AMP_CONSENT_STRING_MAX_LENGTH = 1024;
                    var consentObject = {
                        type: 'consent-response',
                        action: preference && preference.consent ? 'accept' : 'reject'
                    };

                    if (typeof window.__tcfapi === 'function') {
                        __tcfapi('getTCData', 2, function(res) {
                            var consentString = res.tcString;

                            if (consentString.length <= AMP_CONSENT_STRING_MAX_LENGTH) {
                                consentObject.info = consentString;
                            }

                            console.log('send consent-response', consentObject.action, 'with CMP v2 consent string', consentString);
                            window.parent.postMessage(consentObject, '*');
                        });
                    } else if (typeof window.__cmp === 'function') {
                        __cmp('getConsentData', null, function(res) {
                            var consentString = res.consentData;

                            if (consentString.length <= AMP_CONSENT_STRING_MAX_LENGTH) {
                                consentObject.info = consentString;
                            }

                            console.log('send consent-response', consentObject.action, 'with CMP consent string', consentString);
                            window.parent.postMessage(consentObject, '*');
                        });
                    } else {
                        console.log('send consent-response', consentObject.action);
                        window.parent.postMessage(consentObject, '*');
                    }
                }
            }
        };
    </script>
    <script async src="https://cdn.iubenda.com/cs/iubenda_cs.js"></script>
</body>
</html>

In production, you can host this file on: 

Testing environment

Since AMP does not allow the loading of iframes from the same domain, uploading this file on the same domain as your AMP page will result in the cookie notice not being displayed when you load AMP pages from that domain. This issue is only present when testing, because in a real-life AMP scenario the page will be loaded from google.com, so the same-domain issue will never happen.

Anyway, to avoid this issue in non-production use cases, host the HTML file on a different domain or subdomain (e.g. main domain is www.yourdomain.com, but you host the file on amp.yourdomain.com). One easy trick is to use www/non-www redirection to do this without adding extra subdomains.

Also note that the AMP iframe needs to be served via HTTPS.

Step 2 – Edit your AMP pages

Now add a copy of this <amp-consent> to your AMP pages:

<amp-consent id="myUserConsent" layout="nodisplay">
    <!--
      It is preferred to set the consent ID as "consent" + site ID
      If you want to request consent only to EU users then replace "consentRequired": true with "promptIfUnknownForGeoGroup": "eu" -> allows to ask consent only to EU users
    -->
    <script type="application/json">
        {
            "consentInstanceId": "consent896537", //"consent" + site ID
            "consentRequired": "remote",
            "checkConsentHref": "https://amp.iubenda.com/cs/amp/checkConsent",
            "promptUI": "myConsentFlow"
        }
    </script>
    <div id="myConsentFlow" class="popupOverlay">
        <!--
        	Set src attribute to your webpage with the CS for the AMP pages.
        	Note: it must be served over HTTPS
        	See https://cdn.iubenda.com/cs/test/cs-for-amp.html for an example on how to set a page to embed CS
      	-->
        <amp-iframe layout="fill" sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox" src="https://cdn.iubenda.com/cs/test/cs-for-amp.html">
            <div placeholder>Loading</div>
        </amp-iframe>
    </div>
</amp-consent>

Next, add the following to your document head:

<!-- ## Setup -->
<!-- We need to import the `amp-consent` ... -->
<script async custom-element="amp-consent" src="https://cdn.ampproject.org/v0/amp-consent-latest.js"></script>
<!-- ... and the `amp-iframe` extension. -->
<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-latest.js"></script>
<!-- ... the `amp-geo` to only ask consent in EU ... -->
<script async custom-element="amp-geo" src="https://cdn.ampproject.org/v0/amp-geo-latest.js"></script>
<style amp-custom>
    .popupOverlay {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
    }

    amp-iframe {
        margin: 0;
    }

    amp-consent.amp-active {
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        position: fixed;
    }
</style>
<!-- /Setup -->

Note:

  • Add amp-geo only if you want to limit consent collection to EU
  • If these resources are already added to the page, an harmless error will be raised

Step 3 – Block components

As stated on amp.dev/documentation, add data-block-on-consent on all elements that need to be blocked based on consent.

Caution

Per-category consent is not supported by AMP.

Useful tips for WordPress Users

💡 Our WordPress plugin now supports AMP.

A few suggestions:

add_filter('amp_post_template_data', function($data) {
    $data['amp_component_scripts'] = array_merge($data['amp_component_scripts'], array('amp-iframe' => 'https://cdn.ampproject.org/v0/amp-iframe-latest.js'));
    return $data;
});
  • You can then add the rest of the codes directly in the plugin settings (Settings > Advanced Settings).
  • Add the CSS under AMP > Design > Global. AMP validation will fail if scripts and style are not placed in the head and if style is declared more than once: consider linking an external CSS.

See also