2

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.

HahaMuntz
  • 45
  • 8
  • 4
    XMLHttpRequests requests made at beforeunload are also not guaranteed to make it. Most browsers kill off http requests. – epascarello Sep 12 '19 at 13:00
  • 1
    You could potentially send the request synchronously, but even that's still not guaranteed to work in all browsers – Rory McCrossan Sep 12 '19 at 13:17
  • Thanks for letting me know that. Do you have any suggestions for another solution? I just need the server to execute the bat once the user disconnects, that was just the first thing I got working. @Rory McCrossan could you please elaborate on the synchronized request? – HahaMuntz Sep 12 '19 at 15:19
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Synchronous_request – Rory McCrossan Sep 12 '19 at 15:23
  • Thanks, I'll try that. Any idea for the main question? – HahaMuntz Sep 12 '19 at 15:40

0 Answers0