Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Last active February 16, 2022 11:13
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mhawksey/9199459 to your computer and use it in GitHub Desktop.
Save mhawksey/9199459 to your computer and use it in GitHub Desktop.
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),
't':'pageview',
'dl': url };
var payload = Object.keys(data).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
}).join('&');
var options = {'method' : 'POST',
'payload' : payload };
UrlFetchApp.fetch('http://www.google-analytics.com/collect', options);
}
@marekcech
Copy link

marekcech commented Mar 31, 2019

this approach needs to request permission from user otherwise its not working? how to ask for permission or how to make it work around?

for me the onOpen is not working anymore even if I authorize the script, maybe some security precautions in Google Apps Script? can you check?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment