Search code examples
javascriptonbeforeunload

Getting window.confirm to work


I am trying to get window.confirm to work with a script I am working with however it doesn't seem to wanna work . What happens is if the person presses cancel it still runs the code, And sadly now the way i wrote the code the popup box won't even show up in chrome. Not sure why though I can remove the window.confirm method and it will still show a popup box but it will just run the script regardless of which choice you make. Here is the code , Thank you for your assistance.

var validNavigation = false;

function wireUpEvents() {

var dont_confirm_leave = 0; to be able to leave withou confirmation
var leave_message = 'Leaving the page will terminate your Self-Service or Kiosk session.';

function goodbye(e) {
if (!validNavigation) 

    function goodbye() = {
    var x = window.confirm("Leaving the page will terminate your Self-Service or Kiosk session.")
    if (x)
    {
    window.onunload=leave;
    }    
    else            {
    return "" ;
    }
    }}

function leave() {
    if (!validNavigation) {
    killSession();
    }
    }

    //set event handlers for the onbeforeunload and onunloan events
    window.onbeforeunload=goodbye;
    //window.onunload=leave;

            }
    // Wire up the events as soon as the DOM tree is ready
    jQuery(document).ready(function() {
    wireUpEvents();
    });

Solution

  • You can't stop someone from leaving the page - if they want to leave, they can. Stopping this event from propogating in the usual fashion doesn't work. The way to get a popup message to display (which will usually be surrounded by browser supplied text) is to return your string from the function fired by onbeforeunload. Try this:

    function goodbye() {
      if (!validNavigation)
        return "Are you sure you want to leave";
      else
        return "";
    }
    window.onbeforeunload = goodbye;