![](/img/trans.png)
[英]Accessing Google Analytics API data from javascript without authentication
[英]Issue with accessing Google Analytics data with Javascript and API
我想從Google Analytics(分析)中獲取訪問我們網站的訪問者(用戶)數量,最好是使用Javascript。
我已經在Google中設置了一個項目和憑據以與我的雇主的Google Analytics(分析)一起使用,並且能夠獲取該JavaScript示例,該示例生成一個圖表以使其正常工作。
但是,我需要的是度量標准的文本數據,而不是生成的圖表,以便可以將數據包含在我的雇主ASP.NET MVC C#Web應用程序中。
圖表示例與文本數據示例一樣,使用身份驗證按鈕,我可以在其中輸入我的雇主google Analytics(分析)的登錄名和密碼,這對於圖表示例可以正常使用,並且在文本示例中也可以正常使用,但是文本示例運行時未生成數據。
我在此URL上找到了一個示例,用於從Google Analytics(分析)生成文本數據,但僅在運行時會生成錯誤。 https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-js
這是我正在使用的源代碼,在一個HTML文件中,如果有錯誤,請指出。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics Reporting API V4</title>
<meta name="google-signin-client_id" content="xxxxxxx">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>
<h1>Hello Analytics Reporting API V4</h1>
<p>
<!-- The Sign-in button. This will run `queryReports()` on success. -->
<div class="g-signin2" data-onsuccess="queryReports"></div>
</p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Replace with your view ID.
var VIEW_ID = '132296038';
// Query the API and print the results to the page.
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
"reportRequests": [
{
"viewId": VIEW_ID,
"dateRanges": [
{
"startDate": "2017-02-01",
"endDate": "2017-03-16"
}
],
"metrics": [
{
"expression": "ga:sessions"
}
],
"dimensions": [
{ "name": "ga:date" }
]
}
]
}
// }).then(displayResults, console.error.bind(console));
}).then(displayResults, alert(console.error.toString()));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
</body>
</html>
您的代碼有效,因此,我認為您使用的client_id和view_id錯誤,您尚未啟用Google Analytics(分析)Reporting API或API服務器未接受您的主機。
您得到什么錯誤信息? 您的錯誤報告功能不會報告對我有用的任何東西,因此我建議更改:
alert(console.error.toString())
至:
function (error) { alert(error.result.error.message); }
請發布完整的錯誤消息以獲取更多幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.