Last active
February 16, 2022 11:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?