Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Google Apps Script snippet to send tracking data to Google Analytics using the Measurement Protocol
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 data = {'v': '1',
'tid': tid,
'cid': Utilities.getUuid(),
'z': Math.floor(Math.random()*10E7),
'dl': url };
var payload = Object.keys(data).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
var options = {'method' : 'POST',
'payload' : payload };
UrlFetchApp.fetch('', options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment