Skip to content

Instantly share code, notes, and snippets.

@IronistM
Forked from mhawksey/gist:9199459
Created March 7, 2014 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IronistM/9411376 to your computer and use it in GitHub Desktop.
Save IronistM/9411376 to your computer and use it in GitHub Desktop.
function onOpen(){
// example send for Sheets
sendGAMP("UA-XXXX-1", SpreadsheetApp.getActiveSpreadsheet().getUrl());
// example send for Documents
//sendGAMP("UA-XXXX-1", DocumentApp.getActiveDocument().getUrl());
// example send for Forms *NOTE* getUrl not implemented yet in New Sheets
//sendGAMP("UA-XXXX-1", FormApp.getActiveForm().getUrl());
}
/*
* Example function for Google Analytics Measurement Protocol.
* @param {string} tid Tracking ID / Web Property ID
* @param {string} url Document location URL
*/
function sendGAMP(tid, url){
var payload = {'v': '1',
'tid': tid,
'cid': generateUUID_(),
'z': Math.floor(Math.random()*10E7),
't':'pageview',
'dl': url };
var options = {'method' : 'POST',
'payload' : payload };
UrlFetchApp.fetch('https://www.google-analytics.com/collect', options);
}
// http://stackoverflow.com/a/2117523/1027723
function generateUUID_(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment