2

I have a page that searches for flight. If user has clicked the back button in the browser, it should display an error message. I tried the following code: -

   function preventBack(){window.history.forward();}

    setTimeout("preventBack()", 0);

    window.onunload=function(){null};

Problem is that it is not redirecting to a page saying "This document has been expired."

deepz
  • 225
  • 3
  • 13

2 Answers2

1

You can try this:

$(window).on('beforeunload', function () {
    // Prevent back
    alert('This document has been expired.');
    window.history.forward();
});

Also, we have one more option:

$(window).unload(function () {
     // Prevent back
     alert('This document has been expired.');
     window.history.forward();
});

UPDATE:

<script type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • That alert message is not displaying. I kept the above code in page2.php If i press back button, it is going to previous page then back to page2 and refreshing. – deepz Apr 18 '13 at 19:57
1

You can not detect if user has clicked "Back" button natively. The reason you get

This document has been expired

is that you send a new form again and againt on a previous page. This is a great flaw in your architecture.

However if you still insist on this approach, you can use this plugin. Just do a redirect to error page, when a back-click detects. (like window.location = '/path/to/error/page.html')

Yang
  • 8,580
  • 8
  • 33
  • 58
  • 1
    @deepz You're welcome :) However the way you do this thing isn't quite correct. It is 2013 year now. Nobody uses "ancient" form submissions anymore, because they are slow, annoy users etc. Switch to jquery and use ajax instead of form submissions. – Yang Apr 19 '13 at 20:25