Skip to content

Instantly share code, notes, and snippets.

@ryanpraski
Forked from dcvogi/top5pages.js
Created August 9, 2018 18:22
Show Gist options
  • Save ryanpraski/ae9507bcb4b1d4363f4ec83ef066c152 to your computer and use it in GitHub Desktop.
Save ryanpraski/ae9507bcb4b1d4363f4ec83ef066c152 to your computer and use it in GitHub Desktop.
Queries the data for the top 5 pages of the website.
function main(){
// Set up the parameters and variables
var sheetName = '<name>'; // The name of the sheet (not the Spreadsheet) we want to write the data e.g Sheet1
var tableId = '<table id>'; // The id of the view to query the data from e.g ga:123456
var startDate = 'yyyy-MM-dd'; // The start date of the query with the appropriate format e.g 2018-04-01 (1 April 2018)
var endDate = 'yyyy-MM-dd'; // The end date of the query with the appropriate format e.g 2018-04-30 (30 April 2018)
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName(sheetName);
// Set Up the query arguments
var metrics = ['ga:pageviews,ga:avgTimeOnPage,ga:bounceRate'];
var options = {
'dimensions': 'ga:pagePath',
//'filters': '',
'sort': '-ga:pageviews',
//'segment': '',
'samplingLevel': 'HIGHER_PRECISION',
'max-results': '5' // To limit the results to 5. Maximum number of results: 10000
}
// Fetch the report
var report = gaGet(tableId, startDate, endDate, metrics, options);
var data = report.rows;
// Get the range to write and write the results
var writeRange = sheet.getRange(1, 1, data.length, data[0].length) // Read reference for getRange arguments
writeRange.setValues(data);
}
function gaGet(tableId, startDate, endDate, metrics, options) {
// Apply standard options
options = options || {};
options['max-results'] = options['max-results'] || '10000';
// If errors persist up to 5 times then terminate the program.
for (var i = 0; i < 5; i++) {
try {
return Analytics.Data.Ga.get(tableId, startDate, endDate, metrics, options); // 503
} catch (err) {
// https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors
if (err.message.indexOf('a server error occurred') > -1) {
Logger.log('Backend Error');
// Note: Don't listen to Google's reply and retry request after 2 minutes
Utilities.sleep(2 * 60 * 1000);
} else if (err.message.indexOf('User Rate') > -1) {
Logger.log('Rate Limit Error');
// Exponential Backoff
Utilities.sleep(1000 * Math.pow((i + 1), 2));
} else if (err.message.indexOf('too many concurrent connections') > -1) {
Logger.log('Concurrent Connections Error');
// Exponential Backoff
Utilities.sleep(1000 * Math.pow((i + 1), 2));
} else {
Logger.log(err);
throw err;
}
}
}
throw 'Error. Max retries reached';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment