Skip to content

Instantly share code, notes, and snippets.

@nicobrx
Last active August 9, 2016 14:16
Show Gist options
  • Save nicobrx/0c43a1cc51dfc7edb56ec41a67f7cca3 to your computer and use it in GitHub Desktop.
Save nicobrx/0c43a1cc51dfc7edb56ec41a67f7cca3 to your computer and use it in GitHub Desktop.
<script>
/*
* adapted from https://developers.google.com/analytics/devguides/collection/analyticsjs/cross-domain#iframes
* I include the GA object reference in my script, so that one version of
* the script works whether served in an iFrame or on a standalone page.
* I usually have to rely on the 3rd-party vendor to implement the code, so
* I like to keep implementation as simple as possible.
*/
(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');
var trackerCreated = false;
function createTracker(opt_clientId) {
if (!trackerCreated) {
var fields = {};
if (opt_clientId) {
fields.clientId = opt_clientId;
}
ga('create', 'UA-XXXXXXXX-Y', 'auto', fields);
// Google’s sample doesn’t do anything with the tracker
// once created, but presumably you will want to send either a
// GA pageview or event, like I have here.
ga('send', 'pageview');
trackerCreated = true;
}
}
window.addEventListener('message', function(event) {
if (event.origin != 'http://www.xyz.com') return;
createTracker(event.data);
});
// I increased the timeout to 5 seconds to give the message more
// time to arrive.
setTimeout(createTracker, 5000);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment