본문 바로가기

웹 개발

Google Analytics Script API

출처 : http://jsdo.it/nomotch/rMoU 

/**
 * 
 */

//Load the Google data JavaScript client library.
google.load('gdata', '2.x', {packages: ['analytics']});

//Load the Google Libraries jQuery and jQuery UI
//google.load('jquery', '1.5.2');
//google.load('jqueryui', '1.8.12');

//Set the callback function when the library is ready.
google.setOnLoadCallback(init);

/**
 * This is called once the Google Data JavaScript library has been loaded.
 * It creates a new AnalyticsService object, adds a click handler to the
 * authentication button and updates the button text depending on the status.
 */
function init() {
	myService = new google.gdata.analytics.AnalyticsService('gaExportAPI_acctSample_v1.0');
	scope = 'https://www.google.com/analytics/feeds';

	// Add a click handler to the Authentication button.
	jQuery('#authButton').click( function() {
		// Test if the user is not authenticated.
		if (!google.accounts.user.checkLogin(scope)) {
			// Authenticate the user.
			google.accounts.user.login(scope);
		} else {
			// Log the user out.
			google.accounts.user.logout();
			getStatus();
		}
	});
	getStatus();
}

/**
 * Utility method to display the user controls if the user is 
 * logged in. If user is logged in, get Account data and
 * get Report Data buttons are displayed.
 */
function getStatus() {
	jQuery('#getData').click(getAccountFeed);

	if (!google.accounts.user.checkLogin(scope)) {
		jQuery('#dataControls').css('display', 'none');   // hide control div
		jQuery('#authButton').html('Access Google Analytics');

	} else {
		jQuery.datepicker.setDefaults({
			showOn: 'both',
			buttonImageOnly: true,
			buttonImage: 'http://jqueryui.com/demos/datepicker/images/calendar.gif',
			buttonText: 'Calender',
			dateFormat: 'yy-mm-dd' },
			jQuery.datepicker.regional["ja"] );
		jQuery(function(){jQuery('#startDate').datepicker()});
		jQuery(function(){jQuery('#endDate').datepicker()});
		jQuery('#dataControls').css('display', 'block');  // show control div
		jQuery('#authButton').html('Logout');
	}
}

/**
 * Main method to get account data from the API.
 */
function getAccountFeed() {
	var myFeedUri =
		'https://www.google.com/analytics/feeds/accounts/default?max-results=50';
	myService.getAccountFeed(myFeedUri, handleAccountFeed, handleError);
}

/**
 * Handle the account data returned by the Export API by constructing the inner parts
 * of an HTML table and inserting into the HTML file.
 * @param {object} result Parameter passed back from the feed handler.
 */
function handleAccountFeed(result) {
	// An array of analytics feed entries.
	var entries = result.feed.getEntries();

	rows = new Array();

	var table = jQuery('').attr('id', 'outputTable');

	var header = jQuery('').attr('id', 'header').css('text-align', 'center');
	header.append('');
	header.append('');
	header.append('');
	header.append('');
	table.append(header);
	jQuery('#outputDiv').append(table);

	// Iterate through the feed entries and add the data as table rows.
	for (var i = 0, entry; entry = entries[i]; ++i) {

		// Add a row in the HTML Table array for each value.
		var row = {
				'profileId':entry.getPropertyValue('ga:profileId'),
				'title':entry.getTitle().getText(),
				'tableId':entry.getTableId().getValue()
		};

		var tableId = entry.getTableId().getValue();

		rows.push(row);
	}

	getDataFeed();

	/*
  var data = jQuery('').attr('id', 'data');
  data.append('');
  table.append(data);

  jQuery('#outputDiv').append(table);

  getDataFeed(rows[1]['tableId']);
	 */
}

/**
 * Main method to get report data from the Export API.
 */
function getDataFeed() {
	for (var i = 0, row; row = rows[i]; ++i) {
		setTimeout( function(row) {
			var myFeedUri = 'https://www.google.com/analytics/feeds/data' +
			'?start-date=' + jQuery('#startDate').val() +
			'&end-date=' + jQuery('#endDate').val() +
			'&dimensions=ga:entrances' +
			'&metrics=ga:visits,ga:pageviews' +
			'&sort=-ga:pageviews' +
			'&max-results=10' +
			'&ids=' + row['tableId'];

			myService.getDataFeed(myFeedUri, handleDataFeed, handleError);
		}, 5000, row);
	}
}

/**
 * Handle the data returned by the Export API by constructing the 
 * inner parts of an HTML table and inserting into the HTML File.
 * @param {object} result Parameter passed back from the feed handler.
 */
function handleDataFeed(result) {

	// An array of Analytics feed entries.
	var entries = result.feed.getEntries();
	var title = result.feed.getDataSources()[0].getTableName().getValue();
	console.log(title);

	// Iterate through the feed entries and add the data as table rows.
	for (var i = 0, entry; entry = entries[i]; ++i) {

		var data = jQuery('').attr('id', 'data');
		data.append('');
		data.append('');
		data.append('');
		data.append('');
		jQuery('#outputTable').append(data);
		jQuery('td#num').css('text-align', 'center');
	}
}

/**
 * Alert any errors that come from the API request.
 * @param {object} e The error object returned by the Analytics API.
 */
function handleError(e) {
	var error = 'There was an error!\n';
	if (e.cause) {
		error += e.cause.status;
	} else {
		error.message;
	}
	alert(error);
}


Profile Name ga:month ga:visits ga:pageviews
' + rows[1]['title'] + '
' + title + ' ' + entry.getValueOf('ga:month') + ' ' + entry.getValueOf('ga:visits') + ' ' + entry.getValueOf('ga:pageviews') + '