I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload
and onunload
methods are also not working.
How do I detect the window close
, unload
, or beforeunload
events?
A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.
To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.
The best way I found to reload the page without losing cookies, and remove cookies on window or tab close was to use ng-keydown to watch the F5 Keypress (KeyCode 116).
Scripts may close only the windows that were opened by it. A workaround now is redirect user to another page rather than close the window, you could redirect user to a notification page to show "The items has been closed successfully" using window. location.
Have you tried this code?
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; }); });
The second function is optional to avoid prompting while clicking on #lnkLogOut
and .btn
elements.
One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With