I am trying to track how long an user stays on a specific page on my website. I am using sendBeacon, AJAX as Fallback and the Page Visibility API. It works in all browsers and even in Safari when closing or switching the tab.
The problem now is that when I use the navigational links on my website, the tracking doesn't work in Safari but in all other browsers. Here is the code:
// Check Browser Support of sendBeacon
if(navigator.sendBeacon) {
// Check Browser Support of Page Visibility API
var visibilityHidden, visibilityChange;
// Opera 12.10 and Firefox 18 and later support
if(typeof document.hidden !== "undefined") {
visibilityHidden = "hidden";
visibilityChange = "visibilitychange";
} else if(typeof document.mozHidden !== "undefined") {
visibilityHidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
} else if(typeof document.msHidden !== "undefined") {
visibilityHidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if(typeof document.webkitHidden !== "undefined") {
visibilityHidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
if(visibilityHidden !== undefined) {
document.addEventListener(visibilityChange, function() {
if(document[visibilityHidden]) {
var data = new FormData();
data.append('pageid', '{{page::id}}');
data.append('userid', uid);
data.append('language', '{{page::language}}');
data.append('referer', decodeURIComponent(document.referrer));
data.append('start', starts);
data.append('duration', Math.ceil(TimeMe.getTimeOnCurrentPageInSeconds(window.location.href)));
navigator.sendBeacon('/time/', data);
}
});
} else {
sendAjax();
}
Does someone has an idea how to solve this?