javascriptonbeforeunloadonunload

How to call an external function inside onbeforeunload() if the user chooses to move out of the page?


I've seen many examples and tried them out where the specified function gets called if the user decides to stay in the page. I need to call an external function just before the page is unloaded, if the user decides to leave the page.

onbeforeunload = function(){
  if(user decides to leave the page){
      func1();
  }
  else {
    //Don't do anything
  }
}

I tried using "onunload" but I need to prompt the user before calling the function.

Thanks in advance!


Solution

  • You have to use both window.onbeforeunload and window.onunload. onbeforeunload returns a string, and this causes the browser to display a confirmation before leaving. If the user confirms leaving, onunload will be triggered, and then you do what you need before the page is unloaded.

    window.onbeforeunload = function() {
        return "Are you sure you want to leave?";
    };
    window.onunload = function() {
        func1();
    };
    

    There are restrictions on what you can do in both of these event handlers, because you're not allowed to prevent the user from leaving the page if they really want to. Malware used to use these events to do things like reopening the page, now this is prohibited.