Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to detect browser close event

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?

like image 223
vjeta Avatar asked Dec 31 '13 06:12

vjeta


People also ask

How do I find close browser 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.

How detect browser or tab close in react JS?

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.

How do you handle browser tab close angular not close refresh?

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).

How do you fix Scripts may close only the windows that were opened by it?

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.


Video Answer


1 Answers

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.

like image 103
Ravimallya Avatar answered Sep 22 '22 10:09

Ravimallya