+ Start a Discussion
sivassivas 

Detect Browser Close events

I have a requirement in which when we click the 'X' button of the browser, it should open up a warning message with 'OK' and 'Cancel' button just like 'Confirm' box. When we click 'Ok' it should close the window and when we click 'Cancel', the window should not be closed.  

 

Any help on this is highly appreciated.

 

 

Thanks.

bob_buzzardbob_buzzard

I don't think there's a way to do this reliably.  The nearest to it that I've used is the "unload" event, but this is invoked when the page is refreshed as well as when the window is closed.  I have seen javascript functions in the past that determine the mouse coordinates and use that to judge whether the user has clicked the 'x', but obviously that won't work if the user hits alt-f4 or closes via a menu.  I've also had issues with these functions working cross browser.

sivassivas

Thanks for you reply bob. Lets assume that i dont account for 'alt-f4'. Can you send me a sample code for the unload event which pops up a warning when the Visual Force page is closed through 'X' button (Browser: IE7).

 

Thanks.

stephanstephan

Something like this JavaScript should work:

 

 

window.onbeforeunload = function (evt) {
   var message = '!! Leaving this page may cause loss of data !!\n';
   if (typeof evt == 'undefined') evt = window.event;
   if (evt) evt.returnValue = message;
   return message; 
}

 

 

sivassivas

Hi Stephan,

 

Thanks for your reply. This code is working perfectly. As a part of the requirement i have to refresh the same visual force multiple times. Using this code is generating the pop up every time i refresh the page which is undesirable. Is there a way to detect the browser close event based on coordinates?

 

Thanks.

Amit AherAmit Aher

Try using setInterval() method

window.setInterval(function() { 
	window.onbeforeunload = function (evt) {
		let message = 'Leaving this page may cause loss of data!\n';
		if (typeof evt == 'undefined') evt = window.event;
		if (evt) evt.returnValue = message;
		return message; 
	} 
}, 5000);

Note: The message may not work on all the browsers.