这是 2017 年 2 月,不需要编辑 analytics.js,也不需要库或插件,或者至少我不需要它们。过去几年所说的很多东西都已被弃用或过时,所以这是我最新的综合指南。
1. config.xml 文件
在你的config.xml中,你必须允许跨站请求:
<access origin="https://www.google-analytics.com" />
2。 HTML
在您的 CSP 元标记中,如果您选择有一个,您还必须允许调用 Google。它可能看起来像:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' 'unsafe-eval' https://ssl.gstatic.com https://www.google-analytics.com;">
3. javascript
这里是可以在浏览器和 Cordova 打包应用程序中运行的 web 应用程序的注释代码。如果您不关心浏览器,可以忽略 else 块。
// the default GA code, nothing to change
(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','https://www.google-analytics.com/analytics.js','ga');
var fields = {
// note: you can use a single tracking id for both the app and the website,
// don't worry it won't mix the data. More about this in the 3rd section
trackingId: 'UA-XXXXXXXX-Y'
};
// if we are in the app (the protocol will be file://)
if(document.URL.indexOf('http://') !== 0){
// we store and provide the clientId ourselves in localstorage since there are no
// cookies in Cordova
fields.clientId = localStorage.getItem('ga:clientId');
// disable GA's cookie storage functions
fields.storage = 'none';
ga('create', fields);
// prevent tasks that would abort tracking
ga('set', {
// don't abort if the protocol is not http(s)
checkProtocolTask: null,
// don't expect cookies to be enabled
checkStorageTask: null
});
// a callback function to get the clientId and store it ourselves
ga(function(tracker){
localStorage.setItem('ga:clientId', tracker.get('clientId'));
});
// send a screenview event
ga('send', {
// these are the three required properties, check GA's doc for the optional ones
hitType: 'screenview',
// you can edit these two values as you wish
screenName: '/index.html',
appName: 'YourAppName'
});
}
// if we are in a browser
else {
ga('create', fields);
// send a pageview event
ga('send', {
// this is required, there are optional properties too if you want them
hitType: 'pageview'
});
}
3.您的 GA 帐户
如果您不需要监控来自网站的网络应用程序的流量,您可以在此处停止阅读,否则请继续阅读。我假设您使用一个帐户来跟踪网站和应用程序。
- 在创建的视图上应用名为“Application? => yes”的自定义过滤器,以便它只显示
screenview 命中。有官方指南here
- 然后,为了跟踪来自网站的流量,创建
Website 类型的第二个视图。在其上应用自定义过滤器“Application? => no”。
- 如果您想要在线和应用内流量的合并视图,请创建
App 类型的第三个视图。默认情况下(没有过滤器),它将显示所有数据。
补充说明
- 现在一切都通过 https,在您的
<access> 和 CSP 中不再需要 http 协议
- 请注意,在 CSP 中写入
*.google-analytics.com 是行不通的。尽管该策略适用于 Chrome (56),但不适用于 Cordova (5.6.0)
- Google 分析不需要任何应用程序权限,例如我在其他地方读到的 ACCESS_NETWORK_STATE 或 ACCESS_WIFI_STATE
- 所有这些都使用 Android 应用进行了测试(我希望它也可以在 iOS 应用中运行),并安装了 Crosswalk 插件