ActionResult

How to disable browser back button using JavaScript & MVC 5?



Hello everyone,

Today's I have a requirement to disable browsers back button in MVC 5 projects, I have fixed the the above problem using the below  example code.

Table of Contents :
  1. JavaScript code
  2. C# code for MVC ActionResult

Step 1. The JavaScript Code sample

The javascript code put master page of the application for disable the browser back button.


 
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
//This is JavaScript code for "disable browsers back button.
 <script type="text/javascript">   
       function disableBackButtonAllBrowsers() {
            window.history.forward()
        };
        window.onload = disableBackButtonAllBrowsers();
        window.onpageshow = function (evts) { 
                       if (evts.persisted) {
                                disableBackButtonAllBrowsers();
                        }
         };
       
        window.onunload = function () {
                void (0)
        };
 </script>

//This is JavaScript code for "disable browsers back button.
 <script type="text/javascript">    
       function disableBackButtonAllBrowsers() {
            window.history.forward()
        };

        window.onload = disableBackButtonAllBrowsers();
        window.onpageshow = function (evts) {  
                       if (evts.persisted) {
                                disableBackButtonAllBrowsers(); 
                        }
         }; 
      
        window.onunload = function () { 
                void (0) 
        };
 </script>


Step 2. The MVC  example code for controller Action Result

The code sample for MVC controller Action events Result for log-out the applications. Please see the below example code.



01
02
03
04
05
06
07
08
09
10
11
12
//This is MVC 5 code for executing action result.
public ActionResult Logout()
{
    //disable browsers back buttons.
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
    Response.Cache.SetNoStore();
    FormsAuthentication.SignOut();
    return View("Login");
}

//This is MVC 5 code for executing action result.
public ActionResult Logout()
{
    //disable browsers back buttons.
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
    Response.Cache.SetNoStore();

    FormsAuthentication.SignOut();

    return View("Login");
}

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.