0

I'm wondering if there is any solution in JavaScript or JQuery to show the message to the user if they want to close their browser/window? I know there is an option to use beforeunload but the only problem is that I couldn't find what user selects Leave Page or Stay on Page. Reason why I'm asking if this is possible is because if user selects Leave Page I want to process AJAX call and then close the browser. All solutions so far would run AJAX call before user selects the option. Here is example of my current function that I use:

window.addEventListener("beforeunload", function (e) {
    var confirmationMessage = "Your browser is now offline.",
    recID = $.trim($("#recordID").val());

    recID ? removeLock(recID) : ""; // Call function to remove record from the Lock table.
    (e || window.event).returnValue = confirmationMessage; //I'm not sure what is the purpose of this line ???
    return confirmationMessage;
});

As you can see above in the code my removeLock() function will execute as soon as user clicks on the X to close the browser/window. That will remove record from the lock table. This can be the problem if user decides to stay on the page. I'm wondering if there is any alternative solution or the way to check what user selects? Thank you.

espresso_coffee
  • 5,980
  • 11
  • 83
  • 193
  • Possible duplicate of [Capturing result of window.onbeforeunload confirmation dialog](https://stackoverflow.com/questions/5399622/capturing-result-of-window-onbeforeunload-confirmation-dialog) – freedomn-m Dec 13 '17 at 15:11
  • @freedomn-m I already read through that answer. So that means no solution for this case? – espresso_coffee Dec 13 '17 at 15:12
  • You could use a `confirm()` - doesn't look very nice but does block the UI (so doesn't close). Might annoy your users though... – freedomn-m Dec 13 '17 at 15:26
  • @freedomn-m Can you provide an example of how confirm() can be implemented for window/browser closing ? – espresso_coffee Dec 13 '17 at 15:28

1 Answers1

1

I read your post as this may come in handy for tracking user behaviour one day.

I think your question is answered in an older post: Capturing result of window.onbeforeunload confirmation dialog

HTH

h0ger
  • 21
  • 4