JavaScript: how to insert third-party cookies only with the consent of our users

JavaScript: how to insert third-party cookies only with the consent of our users

With JavaScript we can insert those scripts that generate third-party cookies only when users have consented to their use.

With JavaScript we can insert those scripts that generate third-party cookies only when users have consented to their use.

We can use an empty script element in the head section that we're going to dynamically populate with the JavaScript embed code.


<head>
    <script id="ga"></script>
</head>


'use strict';

// https://developers.google.com/analytics/devguides/collection/analyticsjs

const insertGA = target => {
    if(target === null || !target) {
        return false;
    }
    const gaScript = `(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','https://www.google-analytics.com/analytics.js','ga');

                        ga('create', 'UA-XXXXX-Y', 'auto');
                        ga('send', 'pageview');`;
    target.textContent = gaScript;
};

An example:


document.querySelector('#accept-cookies').addEventListener('click', e => {
    e.preventDefault();
    insertGA(document.querySelector('#ga'));
}, false);

By using the textContent property, a browser is now able to make the embed code run.