Search code examples
javascripthtmlonbeforeunload

Can I use " window.onbeforeunload " twice in my html document?


I am creating a HTML layout where user can fill the data and save that page in HTML and JSON formats by using "save" and "save as draft" resp. Can i use

window.onbeforeunload

twice in my template.html file to show two different alert messages?

The alerts would show:

  • when page is empty and user tries to go to load another page
  • when user fills the data in the layout and tries to leave the layout without saving

Solution

  • At first see this example to to understand what will happen if you use it twice, then the idea given bellow

    window.onbeforeunload=function()
    { 
        if(form_empty())
            return "Form is empty"; // message for empty form 
        else
            return "Form is not empty"; // message for filled up form 
    }
    
    function form_empty()
    {
        // check form fields whether the form is empty or not
        // return true if form is empty
        // return false if form is not empty
    }