Google Analytics 2019 and Content-Security-Policy

  • Hi,

    I can use Google Analytics with their snippet inserted after the <head> element,
    but i want to load it dynamically only if my variable GA_MEASUREMENT_ID is set.

    sadly the dynamic loading triggers Content-Security-Policy problems !
    has anyone maybe a clue how to set this up?

    this is my Content-Security-Policy script-src definition :

    Code
    <meta http-equiv="Content-Security-Policy" content="... ; script-src 'self' 'unsafe-inline' www.googletagmanager.com; ..." />


    this is my code using jquery to load google analytics


    and these are the errors i get:

    Code
    [Error] Origin https://my.domain.com is not allowed by Access-Control-Allow-Origin.
    [Error] XMLHttpRequest cannot load https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X due to access control checks.
    [Error] Failed to load resource: Origin https://my.domain.com is not allowed by Access-Control-Allow-Origin.

    best, index

  • Ok.... self-solved *whistling*

    this seems to work :

    Code
    $.getScript("https://www.googletagmanager.com/gtag/js?id="+GA_MEASUREMENT_ID)
    	.done(function() {
    		window.dataLayer = window.dataLayer || [];
    		window.gtag = function() { dataLayer.push(arguments); } // make gtag() global for use in app
    		gtag('js', new Date());
    		gtag('config', GA_MEASUREMENT_ID);
    		console.log('google analytics active!');
    	});


    no special Content-Security-Policy needed

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!