Detecting Browser Close Event
Encountering difficulties in detecting browser close events with customary methods? Fret not, as this detailed guide will provide comprehensive solutions to help you monitor window closure, unloads, or beforeunload events.
解决方案
The following code snippet ingeniously addresses the issue:
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; }); });
This solution incorporates the onbeforeunload event handler, which is triggered before the browser window is closed. The message variable displays a custom prompt, informing the user to save data before leaving the page.
Notably, an auxiliary function is included to prevent the prompt from appearing when clicking specific elements on the page (in this case, the #lnkLogOut and .btn elements).
Firefox Compatibility Consideration
While this code generally functions in other browsers, it's important to note that Firefox may not display the custom prompt. In such cases, alternative methods may need to be considered, as discussed in the linked thread.
The above is the detailed content of How Can I Reliably Detect Browser Close Events and Handle Unsaved Data?. For more information, please follow other related articles on the PHP Chinese website!