Skip to content

Remove Google Tag Manager from Wagtail page previews #476

Open

Description

Initially reported by @vossisboss. In base_page.html, we load Google Tag Manager if configured in the Django settings with no further conditions:

{% if GOOGLE_TAG_MANAGER_ID %}
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{{ GOOGLE_TAG_MANAGER_ID|escapejs }}');
</script>
<!-- End Google Tag Manager -->
{% endif %}
{% endblock meta_tags %}
{% block body_class %}{{ block.super }}{% if page %}template-{{ page.get_verbose_name|slugify }}{% endif %} {% endblock %}
{% block body_top %}
{% if GOOGLE_TAG_MANAGER_ID %}
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5XDDLH" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
{% endif %}
.

In production environments, this means GTM will be loaded for page previews by CMS users. This is problematic for privacy reasons, makes previews slower than they need to be, and adds noise in the analytics.

Instead, we should avoid loading GTM with a conditional on request.is_preview, and probably also is_pattern_library (though that’s not normally enabled in production so most likely not an issue).

Likely patch (untested):

{% if GOOGLE_TAG_MANAGER_ID and not request.is_preview and not is_pattern_library %}
        <!-- Google Tag Manager -->
        <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
            new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                                                      j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','{{ GOOGLE_TAG_MANAGER_ID|escapejs }}');
        </script>
        <!-- End Google Tag Manager -->
    {% endif %}

And:

{% if GOOGLE_TAG_MANAGER_ID and not request.is_preview and not is_pattern_library %}
        <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5XDDLH" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions