Skip to content
CodeWorth
CodeWorth

Code worths when shared

Primary Navigation Menu
Menu
  • BLOG
    • DataBase
    • Programming
    • Mobile
    • Multimedia
    • OS Tips
    • Others
    • Web Development
  • Products
    • Utilities
    • Games
    • JsGenLib
      • PlugIns
      • Core Functions
      • Helper & ShortHands
  • About

JavaScript Prevent Closing of Window with a Confirmation

On August 11, 2010
In Web Development
Tagged JavaScript, Web
With 0 Comments
We might have observed in many sites that they ask user for confirmation upon closing the browser .
Ex : In gmail while we are composing an email if we closed browser tab or window, it will ask for confirmation.

We can implement same in our website by following the below listed steps.
  • Create 2 variables named isNavigationAllowed and onNavigationMessage
    var isNavigationAllowed=false;
    var onNavigationMessage="Closing the page will stop process, is it ok?";
  • Create a function named askForExit() with code given below
    function askForExit()
    {
    	if(!isNavigationAllowed)
    		return onNavigationMessage;
    }
    
  • assign the function to window objects onbeforeload event
    window.onbeforeunload = askForExit;
  • If we want this to confirm only when an operation in progress then we can handle with below code
    //once upload started
    function uploadStarted()
    {
    	window.onbeforeunload =askForExit;
    }
    
    //after completing upload
    function uploadDone()
    {
    	window.onbeforeunload=function(){};
    }
    
  • The problem is this will ask when ever the current page is navigated
    hence also requests for confirmation for Submit button and Links the solution is below
    • Add onsubmit attribute for the form
      onsubmit="isNavigationAllowed=true;"
    • Add onclick attribute for the links(a tags)
      onclick="isNavigationAllowed=true;"
2010-08-11

Subscribe

Enter your email address to receive notifications about new posts via email.

Join 634 other subscribers

Google

Designed using Chromatic WordPress Theme. Powered by WordPress.