keen-tracking.js
keen-tracking.js copied to clipboard
Custom PageViewExit event
Hi guys, by now I'm frustrated because I cannot get it to work: the basic keen pageviewonexit works like a charm. But I need aditional information on one specific page in my react single app.
componentDidMount() {
window.addEventListener("beforeunload", this.onUnload.bind(this))
}
componentWillUnmount()` {
window.removeEventListener("beforeunload", this.onUnload.bind(this))
}
onUnload(e){
const track = client.recordEvent("slide_views",{
'previous_slide' : this.state.current_slide,
'current_slide' : -1,
'previous_slide_total_page_time' : slide_timer.value()
})
Promise.all([track()]).then(() => {return e.resultValue=""})
e.preventDefault(); return e.resultValue="";
}
Any ideas what I'm doing wrong? Is there an easier way to have custom tracking events with keen-tracking.js?
Hi @CyranMS The Autocollector was designed to be easy to implement on static pages. For more advanced uses, React/Vue/Angular apps, we recommend you to use the default Keen-tracking module.
But if you want to just fix the issue - look here to see what exactly happens with our implementation of beforeunload
https://github.com/keen/keen-tracking.js/blob/master/lib/browser-auto-tracking.js#L243
So in your case, something like the code below, should work
componentWillUnmount() {
client.recordEvent({
'collection': 'slide_views',
'previous_slide' : this.state.current_slide,
'current_slide' : -1,
'previous_slide_total_page_time' : slide_timer.value(),
'requestType': 'beaconAPI'
})
}
Note: client variable has to be defined.
Thanks @adamkasprowicz Unfortunately I'm still having trouble with it. Interestingly, events get streamed when the tab is closed in Chrome, but not when I close the whole window. Is this behavior you have observed before?
I Had a quick look into it and its seems the only way to make it reliably work is to use heartbeats to a server, after reading some stackoverflow also this was suggested. In cases where the browser crashes / is closed we will never get an event with the beforeunload method.
Maybe there is a way to use keen.io on the server side so that we fire the browser close event from the server when the users heartbeat dies.
Another idea would be if we can assign a random id for each opened content and then overwrite the last slide value every X seconds of that tracking event. In the keen.io docs i could not find anything yet.