deepz
deepz

Reputation: 225

Expiring a page when back button is clicked

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."

Upvotes: 2

Views: 5499

Answers (2)

Yang
Yang

Reputation: 8711

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')

Upvotes: 1

palaѕн
palaѕн

Reputation: 73926

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="">

Upvotes: 1

Related Questions