Skip to content

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);

This comment has been minimized.

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
You can’t perform that action at this time.