How to Effectively Handle Browser Close Events
Detecting browser close events can be challenging, especially with methods like jQuery's onbeforeunload and onunload not always being reliable. This article provides a solution to detect window close, unload, or beforeunload events effectively.
Solution:
The following JavaScript code can be used to detect browser close events:
window.onbeforeunload = function (event) { var message = 'Important: Please click on \'Save\' button to leave this page.'; if (typeof event == 'undefined') { event = window.event; } if (event) { event.returnValue = message; } return message; }; $(function () { $("a").not('#lnkLogOut').click(function () { window.onbeforeunload = null; }); $(".btn").click(function () { window.onbeforeunload = null; }); });
Optional Implementation:
The second function in the code is optional. It prevents the prompt from displaying when clicking on specific elements, such as #lnkLogOut and .btn.
Note:
It's important to be aware that custom prompts may not work in Firefox. Refer to [this thread](link-to-thread) for more information.
The above is the detailed content of How Can I Reliably Detect Browser Close Events in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!