Search code examples
phpjqueryhtmlajaxonbeforeunload

onbeforeunload while page loads


I'm just curious if things like this is possible >> While still loading a web page, is it possible to return an onbeforeunload like dialog when a user try to navigate to other page or close the browser ?


Solution

  • Well i made this to display a message to be display before someone quits my site, and this gives them the option to stay or leave the page.

    I used jquery so you have to add the link to jquery to your site, yo can do this calling a script tag with the src pointing to the next url: https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js

    and after that just add the next code on your webpage

    $(document).ready(function() 
    {  
       var flag  = true;  
       function Close()
       {  
          if(flag)
          {
             return "Are you sure you want to leave?";}
          }
       }  
       window.onbeforeunload = Close;  
    });  
    

    This will call the Close function at the onbeforeunload event, and will ask if you want to leave or stay

    Hope this helps