-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathHelloAnalytics.html
91 lines (74 loc) · 2.36 KB
/
HelloAnalytics.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics Reporting API V4</title>
</head>
<body>
<button id="auth-button" hidden>Authorize</button>
<h1>Hello Analytics Reporting API V4</h1>
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Replace with your client ID from the developer console.
var CLIENT_ID = '1020428475379-i265lih95a3ips9u6j5c0so8hmpg21kk.apps.googleusercontent.com';
// Replace with your view ID.
var VIEW_ID = '115222200';
// Set the discovery URL.
var DISCOVERY = 'https://analyticsreporting.googleapis.com/$discovery/rest';
// Set authorized scope.
var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];
function authorize(event) {
// Handles the authorization flow.
// `immediate` should be false when invoked from the button click.
var useImmdiate = event ? false : true;
var authData = {
client_id: CLIENT_ID,
scope: SCOPES,
immediate: useImmdiate
};
gapi.auth.authorize(authData, function(response) {
var authButton = document.getElementById('auth-button');
if (response.error) {
authButton.hidden = false;
}
else {
authButton.hidden = true;
queryReports();
}
});
}
function queryReports() {
// Load the API from the client discovery URL.
gapi.client.load(DISCOVERY
).then(function() {
// Call the Analytics Reporting API V4 batchGet method.
gapi.client.analyticsreporting.reports.batchGet( {
"reportRequests":[
{
"viewId":VIEW_ID,
"dateRanges":[
{
"startDate":"7daysAgo",
"endDate":"today"
}],
"metrics":[
{
"expression":"ga:sessions"
}]
}]
} ).then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
});
}
// Add an event listener to the 'auth-button'.
document.getElementById('auth-button').addEventListener('click', authorize);
</script>
<script src="https://apis.google.com/js/client.js?onload=authorize"></script>
</body>
</html>