Skip to content

GDPR-aware content blocking

  • Published: 2024-02-18 22:26

I was wondering how to act upon revoked user consent. Which is beyond the scope of the official mkDocs Material documentation.

mkdocs.yml settings (condensed)

extra_javascript:
  - javascripts/consent.js

plugins:
  - privacy

extra:
  consent:
    title: Cookie notice headline
    description: >-
      Cookie notice teext.
    actions:
      - accept
      - manage
    cookies:
      youtube: (js variable > consent.youtube)
        name: YouTube Nocookie Embeds (Option to check in notice)
        checked: false (Common sense default)

iframe embeds

<iframe width="100%" height="auto"
data-block-src="https://www.youtube-nocookie.com/embed/IDHERE" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
<div data-block-alt>
    <p>This video is blocked according to your <a href=#__consent>Cookie consent preferences.</a></p>
</div>

The consent.js

// Get user consent preferences
var consent = __md_get("__consent")

const dataBlockIframes = document.querySelectorAll('iframe[data-block-src]');

dataBlockIframes.forEach(function(iframe) {
    const src = iframe.getAttribute('data-block-src');

    // Identify YouTube-noocookie embeds, adjust accordingly
    if (src.indexOf('www.youtube-nocookie.com') > -1) {
        function calcHeight() {
            iframe.style.height = `${ iframe.offsetWidth *  0.5625 }px`;
        }
        calcHeight();
        window.addEventListener('resize', calcHeight);
    }

    iframe.removeAttribute('data-block-src');

    const dataBlockAlt = iframe.closest('div')?.querySelector('[data-block-alt]');

    // Display according to consent
    if (consent.youtube) { // Remember the mkdocs.yml variable?
        iframe.setAttribute('src', src);
        if (dataBlockAlt) dataBlockAlt.style.display = 'none';
    } else {
        iframe.style.display = 'none';
        if (dataBlockAlt) dataBlockAlt.style.display = 'block';
    }
})