Skip to content

Instantly share code, notes, and snippets.

@LinzardMac
Created February 9, 2017 00:31
Show Gist options
  • Save LinzardMac/8016bb39d296f155c53b419ea275349c to your computer and use it in GitHub Desktop.
Save LinzardMac/8016bb39d296f155c53b419ea275349c to your computer and use it in GitHub Desktop.
Custom Google Analytics - get web properties
/*
* initialize google analytics
*
*/
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
//Referrer overide code inside GA
if(typeof realReferer != 'undefined' && document.referrer !='' && document.referrer != realReferer){
ga('set', 'referrer', realReferer);
}
var CLIENT_ID = 'XXXXXXXXX';
// // Set authorized scope.
var SCOPES = 'https://www.googleapis.com/auth/analytics.readonly';
function handleClientLoad() {
// Load the API client and auth2 library
gapi.load('auth2', initClient);
}
function initClient() {
gapi.auth2.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: true
}, function (resp) {
makeApiCall(resp);
});
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall(resp) {
var pairedlist = {};
var oauthToken = resp;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.googleapis.com/analytics/v3/management/accounts/57243599/webproperties?key=');
xhr.setRequestHeader('Authorization',
'Bearer ' + oauthToken.access_token);
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
var data=xhr.responseText;
var jsonResponse = JSON.parse(data);
var items = jsonResponse.items;
items.forEach( function(obj){
url = window.location.hostname;
storedurl = obj.websiteUrl;
acctURL = storedurl.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
var theurl = acctURL[2];
pairedlist[theurl] = { 'url' : theurl, 'acct' : obj.id };
console.log(pairedlist[acctURL[2]]);
});
// Save to flat file in DB
var the_data = {
action: 'my_quick_save' ,
data: pairedlist
};
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: the_data,
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
}
};
xhr.send();
}
/**** in the footer ****/
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment