Is it possible to capture the user's answer when using onbeforeunload confirmation?

前端 未结 1 1095
死守一世寂寞
死守一世寂寞 2021-01-13 09:46

I need to warn users that they will lose information when leaving a page. This is easily done using the onbeforeunload event. My problem is that I want to take some action i

相关标签:
1条回答
  • 2021-01-13 10:06

    When leaving the page, the events beforeunload and unload execute, in that order. Of course, if the beforeunload event doesn't complete, the unload event won't.

    The way the beforeunload event doesn't complete is when the user clicks the "Stay on Page" button instead of "Leave Page" (if that dialog is presented to them, like in your code).

    So if you know that the possibility for them to not leave the page will always be presented to them, the only way for the unload event to execute is if the beforeunload event isn't prevented (by the user).

    Therefore, you should be able to put any code that you want to execute when the user actually chooses to leave the page in the unload event.

    As for knowing if the user decided to stay on the page, I'm not sure how to catch it :)

    0 讨论(0)
提交回复
热议问题