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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book