Forked from Dmitry-Klymenko/Google Analytics Custom Task to save all hits to Google Sheets
Created
June 13, 2020 02:44
-
-
Save LCHCAPITALHUMAIN/83d99af59463af391483694d62a435e7 to your computer and use it in GitHub Desktop.
This file contains 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() { | |
return function(model) { | |
var globalSendTaskName = '_' + model.get('trackingId') + '_sendHitTask'; | |
// Hook the sendHitTask - grab an original reference to a function | |
var originalSendTask = window[globalSendTaskName] = window[globalSendTaskName] || model.get('sendHitTask'); | |
model.set('sendHitTask', function(sendModel) { //overwrite sendHitTask with our code | |
var hitPayload = sendModel.get('hitPayload'); | |
//if(hitPayload.indexOf('&ti=') !== -1) { //Capture only Transaction hits | |
if(hitPayload.indexOf('&t=timing') === -1) { //SkipTtimings hits | |
//In the line below, replace YOUR-WEB_APP_URL with the Web App URL (provided to you when you published your Google Sheet web app) | |
var baseUrl = YOUR-WEB_APP_URL;//'https://script.google.com/macros/s/AKfycbyLQZ8Wm_31V5EAnOT1BxGLfzJ1X2bsArqRxOc-xzg1NHqJBmVO/exec'; | |
var collectPayLoad = 'Date='+(new Date().toISOString()); //saving date (note, this is client-based time - be aware of timezones) | |
collectPayLoad += '&Request=' + encodeURIComponent(sendModel.get('hitPayload')); //save full request | |
collectPayLoad += '&GAClientID=' + encodeURIComponent(sendModel.get('clientId')); //save GA browser id/cookie | |
collectPayLoad += '&User-Agent=' + encodeURIComponent(navigator.userAgent); //save User-Agent | |
//add your fields collection here | |
//save dataLayer | |
if(JSON && typeof JSON.stringify === 'function') { | |
//JSON.stringify will fail if there are circular references in your dataLayer. | |
//to simplify the demo, I am not | |
var dlAsJSON = JSON.stringify(window.dataLayer); | |
collectPayLoad += '&DataLayer=' + encodeURIComponent(dlAsJSON); //Data Layer as JSON. | |
} | |
var collectUrl = baseUrl +'?'+ collectPayLoad; | |
//Deliver data to our Google Sheet | |
//In your real project you may consider to use navigator.sendBeacon delivery method | |
var myImage = new Image(); | |
myImage.src = collectUrl; | |
} | |
//Execute original | |
originalSendTask(sendModel); | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment