keen-tracking.js icon indicating copy to clipboard operation
keen-tracking.js copied to clipboard

Custom PageViewExit event

Open CyranMS opened this issue 7 years ago • 4 comments

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?

CyranMS avatar Dec 09 '18 16:12 CyranMS

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.

xrapz avatar Dec 10 '18 11:12 xrapz

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?

CyranMS avatar Dec 11 '18 14:12 CyranMS

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.

theotow avatar Dec 13 '18 01:12 theotow

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.

theotow avatar Dec 13 '18 01:12 theotow