简体   繁体   中英

Time to fire for beforeunload vs. pagehide on iOS

I'm using the beforeunload event to as a means to proxy into metrics about clicks on my site. For example, if beforeunload fires within ~50ms of a click event, I can determine when a user has selected a link.

This gets complicated with iOS, as it doesn't support beforeunload . As per Apple docs, I've substituted pagehide for beforeunload , but this doesn't have the same functionality. It looks as if pagehide replaces unload - NOT beforeunload . In my tests their time to fire differs by ~1500ms on average ( pagehide triggers much later than beforeunload ). This makes attributing pagehide events to clicks very difficult.

Is there any event supported by safari on iOS that can get close to the trigger time of beforeunload ?

NOTE: I know this isn't ideal, and there are other, better approaches which I will likely end up pursuing, but I was still curious about this.

Theoretically pagehide is replacement for beforeunload in safari but practically its not. As correctly observed time to trigger pagehide event can vary because safari fetches the new page in the background and when page is available it fires pagehide .

There is no event if you are looking for one but there is this hack which you can try, as soon as click happens safari stop running requestAnimationFrame . So you can try something like this, as click happens record clickTs and start recording timestamp inside requestAnimationFrame function, now when pageHide fires you just check the time difference between clickTs and eventlastReqAnimTime , it should be roughly between 500 ms. This way you can attribute click to pageHide

var w = window,
reqAnim = null,
clickTs = 'record this when click happens',
eventlastReqAnimTime = +new Date,
logReqAnim = function() {
    eventlastReqAnimTime = +new Date;
    reqAnim = w.requestAnimationFrame(logReqAnim)
};
reqAnim = w.requestAnimationFrame(logReqAnim);
setTimeout(function () {
    w.cancelAnimationFrame(reqAnim);
}, 1500)
w.addEventListener('pagehide', function(){
    if(Math.abs(clickTs - eventlastReqAnimTime) < 500 ){
        console.log('your link was chosen')
    }
})

NOTE: above code is just pseudo, test before running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM