Search code examples
javascriptcode-behind

Intercept selection in window.onbeforeunload dialog


in my web application if the user leaves the current page without having saved changes in the form a pop up window is opened to alert him about that.

For the pop up I use some scripts code injected from codebehind (C#):

var Confirm = true;
window.onbeforeunload = confirmClose;  
function confirmClose() 
{
   if (!Confirm) return;

   if(/*CHECK CHANGE CONDITION IS TRUE*/)
      { return " + WARN_message + "; }
} 

I would need to intercept whether the user click on cancel or ok button.

I tried like:

var button_pressed = window.onbeforeunload = confirmClose;

But it returns always true.

How can get which button was pressed? Thanks


Solution

  • Not possible. There is no event associated with the buttons. What you might be able to do was to see if the user came back by setting a value or perhaps a cookie in the page in the onbeforeunload and test if it is there after some time has passed

    but see the duplicate Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?