我想跟踪用户在网站上完成特定操作所花费的时间(包括服务器响应时间和呈现时间(与 DOM 相关的更改))。
我已经在 Angular 框架中尝试过了。为此,我正在考虑记录用户开始操作的时间,并且我想记下操作完成的时间。作为开发人员,我会知道用户何时开始事件以及用户何时完成搜索、过滤、编辑、添加、删除等操作。因此,我们可以对它们进行区分。但是要记录每个 Action ,我们必须在应用程序的每个部分编写代码。我们可以创建一个插件,以便我们可以在任何地方使用它,而不是在任何地方编写相同的代码来跟踪用户的时间。有什么方法可以创建它吗?或者是否有任何工具可以实现此功能?
最佳答案
这样的事情会有帮助吗?
@Injectable({provideIn: 'root'})
export class TrackingService {
private cache: {[id: number]: {description: string, time: number}} = {};
private id: number = 0;
public startTracking(actionDescription: string): number{
const id = ++this.id;
this.cache[id] = { description: actionDescription, time: new Date().getTime() };
return id;
}
public stopTracking(actionId: number){
const data = this.cache[actionId];
if(data){
const elapsed = new Date().getTime() - data.time;
// ...
// Do something with your 'elapsed' and 'data.description'
// ...
delete this.cache[id];
return {...data, elapsed: elapsed};
}
throw `No action with id [${actionId}] running! `;
}
}
然后在您需要跟踪操作的任何地方转换广告:
private actionId: number;
constructor(private trackingService: TrackingService){}
startAction(){
this.actionId = this.trackingService.startTracking('Description');
}
stopAction(){
const trackingResult = this.trackingService.stopTracking(this.actionId);
}
您可以在某些地方自动跟踪,例如路由:
// app.module.ts
private routeChangeSubscription: Subscription;
private configLoadActionId: number;
private navigationActionId: number;
constructor(private router: Router, private trackingService: TrackingService){
this.routeChangeSubscription = router.events.subscribe((event: Event) => {
if (event instanceof RouteConfigLoadStart) {
this.configLoadActionId = this.trackingService.startTracking('configLoad');
}
else if (event instanceof RouteConfigLoadEnd) {
const result = this.trackingService.stopTracking(this.configLoadActionId);
// ... process the result if you wish
}
else if (event instanceof NavigationStart) {
this.navigationActionId = this.trackingService.startTracking('navigation');
}
else if (event instanceof NavigationEnd) {
const result = this.trackingService.stopTracking(this.navigationActionId);
// ... process the result if you wish
}
});
}
或者对于 HTTP 请求:
// http-tracking.interceptor
export class HttpTrackingInterceptor implements HttpInterceptor {
constructor(private trackingService: TrackingService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const actionId = this.trackingService.startTracking('HTTP request');
return next.handle(req.clone()).pipe(
tap(r => this.trackingService.stopTracking(actionId))
);
}
}
// app.module.ts
@NgModule({
// ... other module stuff
providers: [
// ... other providers
{
provide: HTTP_INTERCEPTORS,
useClass: HttpTrackingInterceptor,
multi: true,
deps: [TrackingService]
}
]
})
export class AppModule { ... }
您可以轻松地扩展 TrackingService
以返回 Promises 或 Observables 或其他任何东西,如果您愿意...
希望这对您有所帮助:-)
关于javascript - 跟踪用户在网站中完成特定操作的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50698676/