I am Trying with onbeforeunload, and Unload function. But it didn't work. When clicking a link or refreshing, this event got triggered. I want an event that is triggered only when a browser window or tab is closed. The code must work in all browsers.
I am using Following code in Masterpage.
<script type="text/jscript"> var leaving = true; var isClose = false; function EndChatSession() { var request = GetRequest(); request.open("GET", "../Chat.aspx", true); request.send(); } document.onkeydown = checkKeycode function checkKeycode(e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; if (keycode == 116) { isClose = true; } } function somefunction() { isClose = true; } window.onbeforeunload = function (e) { if (!e) e = event; if (leaving) { EndChatSession(); e.returnValue = "Are You Sure"; } } function GetRequest() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { //Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } </script>
and in my body tag:
The Above code works in IE but not in chrome...
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.
JavaScript provides an event handler called beforeunload. This event is called whenever the resources are removed/unloaded from the client. This means this event will be triggered whenever the user either reloads the page, closes the tab or the browser window.
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).
This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)
window.onbeforeunload = function () { return "Are you sure?"; } $(function () { $('input[type="checkbox"]').click(function () { window.onbeforeunload = function () { }; }); });
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