The example in this article describes the method of using js to prompt the user whether to leave the page before leaving the page (including browser button events). Share it with everyone for your reference. The details are as follows:
Before the user leaves the page, prompt whether to leave this page (including browser button events)
<script type="text/javascript"> window.onbeforeunload = function(){ return "您的文章尚未保存!"; } </script>
If a dialog box needs to pop up when exiting the page, prompting the user to exit the page, similar to setting a certain function without saving the page. The implementation method is relatively simple. The most common one is to use the unload event. However, this implementation has a disadvantage. Regardless of whether you agree or not, the result is still the same and the page will exit. Therefore, if a dialog box is to pop up, the user has a choice. space, exit if confirmed, otherwise the page will not be closed
It is recommended to use the onbeforeunload() event, which means the method is executed before loading the unload event. Use the following:
<script type="text/javascript"> window.onbeforeunload = function(){ return "必您确定要退出页面吗?"; } </script>
A dialog box will pop up, and only confirmation will exit the page.
window.onbeforeunload can be combined with jQuery to achieve a prompt effect when the user sets the page but has not saved it. That is, if it has been saved, the dialog box should not be prompted. You can use the following method, when it is not needed
Prompt dialog box:
<script type="text/javascript"> window.onbeforeunload = function(){ return; } </script>
This will exit the page directly without any dialog box popping up.
Combining jQuery to implement Javascript exit page pop-up dialog box is to combine the above two methods. When the page meets a certain situation, if a dialog box needs to pop up, it will pop up. Otherwise, the dialog box will not pop up. This is very convenient. jQuery has its own unload method, but it also cannot return. There is only one result, which is to exit the page. Therefore, combined with window.onbeforeunload, it will be possible to realize the function of exiting the page and popping up a dialog box.
I hope this article will be helpful to everyone’s JavaScript programming design.