I'm trying to run a bat on the server every time the user leaves the site.
I got that part working by using beforeunload
, of course it triggers every time the page got unloaded.
So I added a flag when the user clicks on a link and that works too.
Now only back/forward and reload trigger the bat and I'm not sure how to prevent that.
I found this solution https://stackoverflow.com/a/36444134/9552448 but it doesn't always work.
It only works if the page got loaded either through back/forward or a reload, but not when it gets loaded by a link.
Here is my javascript:
<script language="JavaScript">
var linkClicked = 0;
$("a").click(function(){
linkClicked = 1;
});
window.addEventListener('beforeunload', function (e) {
if (linkClicked == 0) {
var xhttp = new XMLHttpRequest();
if (window.performance) {
console.info("window.performance works fine on this browser");
}
if (window.performance.navigation.type == 1) {
console.info("Used reload");
}
else if (window.performance.navigation.type == 2) {
console.info("Used backward/forward");
}
else {
xhttp.open("GET", "/bat/", true);
xhttp.send();
}
}
});
</script>
Please let me know if you need additional info.
Any suggestions to achieve running the bat only when the user leaves would be appreciated.
Thanks in advance for any help.