Monday, December 11, 2017

How to prevent users from going back to the previous page?

Leave a Comment

I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

[NoBrowserCache] public ActionResult Page1(int userId) {    var user = GetUserFromDb(userId);    if (user.HasAlreadySubmittedPage1InThePast)    {       // forward to page 2       return RedirectToAction("Page2", routeValues: new { userId = userId });    }     var model = new Page1Model();     return View("Page1", model); }  [NoBrowserCache] [HttpPost] public ActionResult Page1(Page1Model model) {    var user = GetUserFromDb(model.UserId);    if (user.HasAlreadySubmittedPage1InThePast)    {        // forward to page 2        return RedirectToAction("Page2", routeValues: new { userId = model.UserId });    }     // Save posted data to the db    // ...     return RedirectToAction("Page2", routeValues: new { userId = model.UserId }); }  public class NoBrowserCache : ActionFilterAttribute {     public override void OnActionExecuting(ActionExecutingContext filterContext)     {         // Haha ... tried everything I found on the web here:          // Make sure the requested page is not put in the browser cache.          filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);         filterContext.HttpContext.Response.Cache.SetNoStore();         filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");         filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);         filterContext.HttpContext.Response.Expires = 0;     } } 

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12 Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the <head> section of my _Layout.cshtml:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Expires" content="0"> 

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12 Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

enter image description here

5 Answers

Answers 1

Finally I found a solution. It's javascript based, but very simple.

I just had to add the following snippet to my Page-2 (the page I don't want users to leave anymore once they got there):

<script type="text/javascript">  $(document).ready(function () {     history.pushState({ page: 1 }, "title 1", "#nbb");     window.onhashchange = function (event) {         window.location.hash = "nbb";     }; }); 

I found this here: how to stop browser back button using javascript

Thanks to all your support guys. But "my own" solution was the only one that worked.

Answers 2

You can add a line of javascript to every page for a client-side solution:

history.forward();

See docs on MDN. When there is a page to go forward to (which is when the used pressed the BACK button), this will force the user to that page. When the user already is at the most recent page, this does nothing (no error).

Answers 3

Response.Cache.SetCacheability(HttpCacheability.NoCache);  // HTTP 1.1. Response.Cache.AppendCacheExtension("no-store, must-revalidate"); Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0. Response.AppendHeader("Expires", "0"); // Proxies. 

Answers 4

This little piece of code might help you in solving your issue.

<script type="text/javascript">                 /*To retain on the same view on Back Click*/                 history.pushState(null, null, window.location.href);                 window.addEventListener('popstate', function (event) {                     history.pushState(null, null, window.location.href);                     event.preventDefault();                     }); </script> 

Answers 5

This can be done by using javascript. Use the following code

     <script type = "text/javascript" >    function preventBack(){window.history.forward();}     setTimeout("preventBack()", 0);     window.onunload=function(){null};    </script> 

or check the following link1 and link2.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment