You are not logged in.

1

Wednesday, September 11th 2019, 6:20pm

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 :

Source code

1
<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

Source code

1
2
3
4
5
6
7
8
9
10
11
var GA_MEASUREMENT_ID = 'UA-XXXXXXXX-X'; // set dynamically from configuration file
$.ajax({
	url: "https://www.googletagmanager.com/gtag/js?id="+GA_MEASUREMENT_ID,
	success: function() {
		window.dataLayer = window.dataLayer || [];
		function gtag() { dataLayer.push(arguments); } 
		gtag('js', new Date());
		gtag('config', GA_MEASUREMENT_ID);
		console.log('google analytics is active!');
	}
});

and these are the errors i get:

Source code

1
2
3
[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

This post has been edited 3 times, last edit by "indexofrefraction" (Sep 11th 2019, 6:35pm)


2

Wednesday, September 11th 2019, 10:22pm

Ok.... self-solved *whistling*

this seems to work :

Source code

1
2
3
4
5
6
7
8
$.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