我可以使用另一个跟踪器Riveted,它的定义是:
Riveted 通过测量用户积极参与的时间量(例如,点击、滚动、使用键盘),然后定期将数据报告给 Google Analytics 来帮助解决这个问题。
更多关于它的页面。
虽然Riveted是使用直接全局变量编写的,但我们需要使用exports-loader使其可用于 react 项目。
这是我可以实现的目标:
在本地获取 riveded.js 作为文件
确保通过安装 exports-loadernpm install exports-loader --save
导入与 as 的位置相同revited.js
:
import riveted from 'exports-loader?exports=riveted!./riveted.js';
初始化后ReactGA.initialize(configs);
如果您检查rived 的源代码,您会注意到它使用的是相同的ga
对象,window.ga
因此一旦通过初始化谷歌分析就ReactGA.initialize
足够了。
react-ga
提供了扩展的能力ga
。它们的状态ga
可以通过ReactGA.ga()
方法访问。This gives developers the flexibility of directly using ga.js features that have not yet been implemented in ReactGA. No validations will be done by ReactGA as it is being bypassed if this approach is used.
然后ga
允许编写自定义插件
所以这就是代码的样子:
import React, { PureComponent } from 'react';
import ReactGA from '../../src';
import riveted from 'exports-loader?exports=riveted!./riveted.js';
export default class App extends PureComponent {
constructor(props, context) {
super(props, context);
this.state = {
reactGaInitialised: false,
configs: [DEFAULT_CONFIG]
};
}
initReactGA = (event) => {
const { configs } = this.state;
ReactGA.initialize(configs);
// Send initial test view
ReactGA.pageview('test-init-pageview');
function TrackerCustomPlugin() {
this.riveted = riveted;
}
TrackerCustomPlugin.prototype.init = riveted.init;
let ga = ReactGA.ga();
ga('provide', 'riveted', TrackerCustomPlugin);
ga('require', 'riveted');
ReactGA.plugin.execute('riveted', 'init', {
reportInterval: 10, // Default: 5
idleTimeout: 20, // Default: 30
nonInteraction: true // Default: true
});
};
以下是事件如何从我的本地发送到 GA:

GA仪表板显示Time Spent
:
