Click here to Skip to main content
15,894,337 members
Articles / Programming Languages / Javascript
Tip/Trick

Browser Back Button Alert/Confirm Message Functionality

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Mar 2014CPOL 24K   2   4  
Browser Back Button Alert/Confirm message functionality

Introduction

I have implemented the Browser back button functionality in our project.

I have used JavaScript to implement the functionality.

Below is the code:

JavaScript
<script language="javascript" type="text/javascript">
window.onbeforeunload = function()
{
    return "Are you sure want to close";
}
</script>

The above code will execute on every postback. The alert message will appear on any click event like button, links, hyperlinks, etc.

If we don’t want this message on click of buttons and links, we have to implement the below code:

JavaScript
<script language="javascript" type="text/javascript">
          window.onload = function() {
   var btnRelease = document.getElementById('<%= btnRelease.ClientID %>');
                  
//Find the button set null value to click event and alert will not appear for that specific button

                  function setGlobal() {
                      window.onbeforeunload = null;
                  }
                  $(btnRelease).click(setGlobal);

 // Alert will not appear for all links on the page
                  $('a').click(function() {
                      window.onbeforeunload = null;

                  });
                  window.onbeforeunload = function() {
                          return 'Are you sure you want to leave this page?';
                  };
             
          };
      }   
 </script>

Now alert/confirm message will appear only on back button of browser.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --