我正在尝试从 Google Analytics 获取我们网站的访问者(用户)数量,最好使用 Javascript。
我已经在 Google 中设置了一个项目和凭证以使用我雇主的 Google Analytics,并且能够获得生成图表的 javascript 示例以正常工作。
但是我需要的是指标的文本数据而不是生成的图表,这样我就可以将数据包含在我的雇主 ASP.NET MVC C# 网络应用程序中。
图表示例与文本数据示例一样,使用了一个身份验证按钮,我可以在其中输入我的雇主 google 分析的登录名和密码,这对图表示例来说是正确的,而且对于文本示例来说似乎也能正常工作,但是文本示例在我运行时未生成数据。
我在此 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); }
请发布完整的错误消息以获得进一步的帮助。
关于javascript - 使用 Javascript 和 API 访问 Google Analytics 数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42864429/