I need to somehow detect that the user has pressed a browsers back button and reload the page with refresh (reloading the content and CSS) using jquery.
How to detect such action via jquery?
Because right now some elements are not reloaded if I use the back button in a browser. But if I use links in the website everything is refreshed and showed correctly.
IMPORTANT!
Some people have probably misunderstood what I want. I don't want to refresh the current page. I want to refresh the page that is loaded after I press the back button. here is what I mean in a more detailed way:
user is visiting page1.
while on page1 - he clicks on a link to page2.
he is redirected to the page2
now (Important part!) he clicks on the back button in browser because he wants to go back to page1
he is back on the page1 - and now the page1 is being reloaded and something is alerted like "You are back!"
You can use pageshow event to handle situation when browser navigates to your page through history traversal:
window.addEventListener( "pageshow", function ( event ) {
var historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( historyTraversal ) {
// Handle page restore.
window.location.reload();
}
});
Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true ). But I don't think that it is best solution.
For more information check:
Working with BFCache article on MDN
WebKit Page Cache II – The unload Event by Brady Eidson
pageshow event reference on MDN
Ajax, back button and DOM updates question
JavaScript - bfcache/pageshow event - event.persisted always set to false? question
Back/Forward Cache
It's been a while since this was posted but I found a more elegant solution if you are not needing to support old browsers.
You can do a check with
performance.navigation.type
Documentation including browser support is here: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
So to see if the page was loaded from history using back you can do
if(performance.navigation.type == 2){
location.reload(true);
}
The 2 indicates the page was accessed by navigating into the history. Other possibilities are-
0:The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.
1:The page was accessed by clicking the Reload button or via the Location.reload() method.
255: Any other way
These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
Note Performance.navigation.type is now deprecated in favour of PerformanceNavigationTiming.type which returns 'navigate' / 'reload' / 'back_forward' / 'prerender': https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type
Since performance.navigation is now deprecated, you can try this:
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload();
}
jQuery( document ).ready(function( $ ) {
//Use this inside your document ready jQuery
$(window).on('popstate', function() {
location.reload(true);
});
});
This will work 100% when back or forward button has been clicked; also if using ajax.
If it doesn't -- there must be a misconfiguration in a different part of the script.
For example: it might not reload the page if some page (in the previous post) is setting the state to:
window.history.pushState('', null, './');`
so when you do use history.pushState();
make sure you use it properly!
In most cases you will use:
history.pushState(url, '', url);
Not window.history ... and make sure url is defined.
An alternative that solved the problem to me is to disable cache for the page. That make the browser to get the page from the server instead of using a cached version:
Response.AppendHeader("Cache-Control","no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");
Currently this is the most up to date way reload page if the user clicks the back button.
const [entry] = performance.getEntriesByType("navigation");
// Show it in a nice table in the developer console
console.table(entry.toJSON());
if (entry["type"] === "back_forward")
location.reload();
See here for source
You should use a hidden input as a refresh indicator, with a value of "no":
<input type="hidden" id="refresh" value="no">
Now using jQuery, you can check its value:
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? location.reload(true) : $input.val('yes');
});
When you click on the back button, the values in hidden fields retain the same value as when you originally left the page.
So the first time you load the page, the input's value would be "no". When you return to the page, it'll be "yes" and your JavaScript code will trigger a refresh.
I tried all the solutions from the previous answers. No one worked.
Finally I found this solution, which did worked:
(function () {
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload();
}
};
})();
JS Solution That Works On Most Browsers
None of the many other approaches on this page worked for me, perhaps because the "bfcache" is preventing anything from happening when the user navigates back to the page. However, I found that registering a window.onbeforeunload handler works for me in most browsers, and I believe it works because it implicitly invalidates the "bfcache". Here's the code:
window.onbeforeunload = function() {
window.location.reload(true);
}
This event may be triggered in other cases than "back" button navigation, but it my case that doesn't matter. I tested this on the following platforms on recent versions of the listed browsers in August 2021:
Linux: works in Chrome and Firefox.
Android: works in Chrome, Firefox, and Opera.
OS X: works in Chrome and Safari.
iOS: doesn't work in Safari.
In my case I don't really care about mobile. I do care about IE, but don't have access to IE, so I couldn't test it. If someone tries this on IE and can report the result in the comments that would be helpful.
Server Side Response Headers That Fix iOS Safari
I found that iOS Safari also works if I invalidate the browser cache using Cache-Control response header. I.e. sending
Cache-Control: no-store, must-revalidate
fixes iOS Safari. See this SO answer for how to set the Cache-Control response header on various platforms.
Reload is easy. You should use:
location.reload(true);
And detecting back is :
window.history.pushState('', null, './');
$(window).on('popstate', function() {
location.reload(true);
});
I had the same problem, back-button would update the url shown in location field but page-content did not change.
As pointed out by others it is possible to detect whether a change in document.location is caused by back-button or something else, by catching the 'pageshow' -event.
But my problem was that 'pageshow' did not trigger at all when I clicked the back-button. Only thing that happened was the url in location-field changed (like it should) but page-content did not change. Why?
I found the key to understanding what was causing this from: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event .
It says 'pageshow' -event is caused among other things by "Navigating to the page from another page in the same window or tab" or by "Returning to the page using the browser's forward or back buttons"
That made me ask: "Am I returning to the page, really?". "What identifies a page?". If my back-button did something else than "returning to the page" then of course 'showpage' would not trigger at all. So was I really "returning to a page"? OR was I perhaps staying on the same "page" all the time? What is a "page"? How is a page identified? By a URL?
Turns out me clicking the back-button did NOT "change the page" I was on. It just changed the HASH (the # + something) that was part of my url. Seems the browser does not consider it a different page when the only thing that changes in the URL is the hash.
So I modified the code that manipulates my urls upon clicking of my buttons. In addition to changing the hash I also added a query parameter for which I gave the same value as the hash, without the '#'. So my new URLs look like:
/someUrl?id=something#something
Every page that my app considers to be a "different page" now has a different value for its query-string parameter 'id'. As far as the browser is concerned they are different "pages". This solved the problem. 'Pageshow' -event started triggering and back-button working.
This works in Nov 21 in latest Firefox and Chrome.
window.addEventListener( "pageshow", function ( event ) {
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload();
}
});
Use following meta tag in your html header file, This works for me.
<meta http-equiv="Pragma" content="no-cache">
In Chrome 96 perfEntries[0].type is 'reload', when you use the back button
Here is a version that detects for Safari, and if detected executes the older code that is officially deprecated (but is still in Safari).
let isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
navigator.userAgent &&
navigator.userAgent.indexOf('CriOS') == -1 &&
navigator.userAgent.indexOf('FxiOS') == -1;
if(isSafari) {
window.addEventListener( "pageshow", function ( event ) {
let historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if (historyTraversal) {
// Handle page restore.
window.location.reload();
}
});
} else {
let perfEntries = performance.getEntriesByType("navigation")
if (perfEntries[0].type === "back_forward") {
window.location.reload(true);
}
}
I found the best answer and it is working perfectly for me
just use this simple script in your link
next page
or the button click event
<INPUT TYPE="button" onClick="history.go(0)" VALUE="next page">
when you use this, you refresh your page first and then go to next page,
when you return back it will be having the last refreshed state.
I have used it in a CAS login and gives me what I want.
Hope it helps .......
details found from here
Related
I have the following Ajax logon script. index.php will set a session and then return something like {"status":true,"msgs":[],"url":"\/demo\/administrator\/index.php"}if the username and password checks out. The page then should reload, the PHP script will check if the session is set, and if so, will display the appropriate page.
"Sometimes" with FireFox 21.0 running on Windows 7, the page appears to reload, but then incorrectly re-displays the logon page. When I say "appears to reload", when using FireBug, I see the POST to the server, I then see the console.log "reload page" for a brief amount of time, and then the logon page is displayed. If I then manually reload the page, the session checks out, and the correct page is returned.
To troubleshoot, I put some syslog(LOG_INFO,"got here!"); in my PHP script, and I see it never got accessed a second time, thus my believe the server isn't getting hit after the reload. I've also checked the Apache access log, and I believe it only sees the first POST.
Can anyone let me know what is happening, and how to remedy it? Thank you
$.post('index.php',{task:'logon',username:username,password:password},
function (data)
{
if(data.status==true){
console.log('reload page');
//window.location.href = data.url;
window.location.href = window.location.href;
//window.location.reload();
}
else {msgs.html("<ul>"+mkList(data.msgs)+"</ul>");}
},'json'
);
This answer was really provided by Brian Lacy and user1600124, but they only left comments and didn't post this answer. So, please vote their comments up if you think this is a good answer.
Use window.location.reload(true) to submit data to server
If you don't explicitly tell the browser not to cache pages in the headers.. some browsers will still cache dynamic pages because the parameter that you send is the same.
As an alternate solution, you can append a timestamp to the url that would force browser to get content from server again.
also setting the pragma "no-cache" header for your page could help.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Avoiding_caching
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a way to catch the back button event in javascript?
In my application I want only a certain number of scripts (Text1.php, Text2.php and Text3.php) to contain a piece of code where that if the user clicks on the back browser button, it will display a confirmation box like the one below:
confirm("You have clicked on the browser's back button. If you confirm to go back via the browser back button, you will be logged out and lose your current assessment details." + "\n" + "\n" + "Are you sure you want to go back and lose current assessment details?" + "\n" );
The requirments are the following:
How to show the confirm if the user clicks on the back browser button?
If user confirms the confirmation then navigate to Text4.php (This is where it logs out user)
If user cancels confirmation then just close confirmation box so user can continue what they are doing (guessing this is something to do with return false;
Only want this to happen for scripts (Text1.php, Text2.php and Text3.php)
Need it to work on all major browsers (IE, Chrome, Firefox, Safari, Opera)
Thank you
Note: You should ONLY do this if you NEED to prevent the person from leaving (that is, if they've inputted some important data and will lose it by navigating away). Also note that you cannot customize the confirmation popup in more recent browsers. (Older browsers allowed customizing the confirmation message body.) These are the restrictions of such a feature.
You can use the beforeunload event to achieve this. In older browsers, you could return a custom string for the confirmation prompt:
$(window).bind("beforeunload", function() {
return "HI"; // This will be shown in the confirmation popup in older browsers.
});
However, as mentioned by #formicini in the comments, more recent browsers (Chrome 87, for example) do not allow a custom string. Returning any non-undefined value will show the confirmation prompt, but will just display the browser's generic message—even if it's a string.
$(window).bind("beforeunload", function() {
return true; // Any non-undefined value will show generic confirmation popup.
});
I would also suggest you unbind this upon someone leaving the page in the desired way (a cancel button?), or you may run into undesirable behavior.
For example:
$("a").click(function() {
$(window).unbind("beforeunload");
});
Can not because a browser security restriction but You can tell if the user navigates away from the page.
you can detect user leave page by this function
window.onbeforeunload = function (e) {
var message = 'Are you sure ?';
if (typeof e == 'undefined') {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
I have a web page, let's call it main.php which displays an image of football field and some players distributed on the field. However, that page uses list.php as a right side frame that loads a list of players.
What happens is, when the user clicks on a player on the field (main.php), let's say on the image of the Goal Keeper (GK), a list of GKs from world wide teams will load in right list fram (list.php). This is by using ajax.
So far we are good.
The current situation is, when session times out and the user clicks on a player from the field, the list on the right does not load, instead, list of players disappears from the list and a message says "Please login" is displayed on the right side frame (list.php)
The objective is, when session times out I want the whole website to redirect to the main page index.php
The problem is, I already put the redirecting code just before the code that is responsible of displaying the message "Please login". But what happened is, the redirection happens from within the frame, so i ended up having main.php displaying the field, and list.php displaying the main page!
Here's the code I added.
$user_id = NSession::get('user_id');
if (!isset($user_id))
{
NSession::removeall();
General::Redirect('index.php');
}
They are using Smarty. and btw, I added the same code to top of main.php, and now if user tries to access main.php without logging in, it will redirect him to the main page, so the code works!
n.b. The project is not mine, it belongs to the company I work in.
And I don't know which code is checking the session, all what I know is, if the user click on a player from the field after the session timeout, the "Please Login" message will be shown in the frame.
I'm guessing the redirect is essentially the same as using a header() function. It isn't possible to specify a target using a php redirect as it is server-side - specifying the target is client-side.
You would need to print something like this to the screen:
<script type="text/javascript">window.open('index.php','_parent');</script>
And that will redirect the user to the index.
Using frames for such purpose is... well... so 80ish...
Anyway, the frames are probably named in such a scenario. This means you can address them, but also that you have to address them. Just loading an url inside the "current" frame does exactly that, which is why your approach won't work.
If you really have to go with that frame based approach, then you will have to use javascript to address all known frames and redirect them.
Maybe you can use some javascript inside of your frame like so :
<script type="text/javascript">
window.top.location = 'YourPage.html';
</script>
Hope this helps
The issue was that the session expires while I'm on main.php. Therefore, any subsequent Ajax requested will fail since all requests requires session to be active.
the problem was that the Ajax request being sent from the IFrame (the IFrame is inside main.php and points to list.php thru Ajax calls) is failing due to session expiry.
So I've fixed this issue by adding another two session checks, one on main.php, list.php using PHP (check for session, if it's there, redirect). And in the main container, main.php, I check for the session via JS, interval Ajax requests to check the session, if session has ended, then use redirect using JS.
PHP:
$user_id = NSession::get('user_id');
if (isset($_POST["checklogin"]))//check loging
{
die(isset($user_id) ? "true" : "false");
}
if (!isset($user_id) || $user_id == "")
{
NSession::removeall();
General::Redirect('login.php');
}
JavaScript:
jQuery(document).ready(function($) {
$(window).focus(function() {
checkSession();
});
});
function checkSession()
{
$.ajax({
type: "POST",
data: {"checklogin": "cl"},
url: "list_players.php",
success: function(result) {
if (result === "false")
{
if (FIELD.showMessage === false)
{
FIELD.showMessage = true;
alert("Your session has been closed\nYou will be redirected to login page now. ");
window.location.href = ("login.php");//incase user clicks OK
}
}
}
});
}
How do I clean information in a form after submit so that it does not show this error after a page refresh?
See image (from chrome):
The dialog has the text:
The page that you're looking for used
information that you entered. Returning to that
page might cause any action you took to be
repeated. Do you want to continue?
I want this dialog not to appear.
This method works for me well and I think the simplest way to do this is to use this javascript code inside the reloaded page's HTML.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
Edit: It's been a few years since I originally posted this answer, and even though I got a few upvotes, I'm not really happy with my previous answer, so I have redone it completely. I hope this helps.
When to use GET and POST:
One way to get rid of this error message is to make your form use GET instead of POST. Just keep in mind that this is not always an appropriate solution (read below).
Always use POST if you are performing an action that you don't want to be repeated, if sensitive information is being transferred or if your form contains either a file upload or the length of all data sent is longer than ~2000 characters.
Examples of when to use POST would include:
A login form
A contact form
A submit payment form
Something that adds, edits or deletes entries from a database
An image uploader (note, if using GET with an <input type="file"> field, only the filename will be sent to the server, which 99.73% of the time is not what you want.)
A form with many fields (which would create a long URL if using GET)
In any of these cases, you don't want people refreshing the page and re-sending the data. If you are sending sensitive information, using GET would not only be inappropriate, it would be a security issue (even if the form is sent by AJAX) since the sensitive item (e.g. user's password) is sent in the URL and will therefore show up in server access logs.
Use GET for basically anything else. This means, when you don't mind if it is repeated, for anything that you could provide a direct link to, when no sensitive information is being transferred, when you are pretty sure your URL lengths are not going to get out of control and when your forms don't have any file uploads.
Examples would include:
Performing a search in a search engine
A navigation form for navigating around the website
Performing one-time actions using a nonce or single use password (such as an "unsubscribe" link in an email).
In these cases POST would be completely inappropriate. Imagine if search engines used POST for their searches. You would receive this message every time you refreshed the page and you wouldn't be able to just copy and paste the results URL to people, they would have to manually fill out the form themselves.
If you use POST:
To me, in most cases even having the "Confirm form resubmission" dialog pop up shows that there is a design flaw. By the very nature of POST being used to perform destructive actions, web designers should prevent users from ever performing them more than once by accidentally (or intentionally) refreshing the page. Many users do not even know what this dialog means and will therefore just click on "Continue". What if that was after a "submit payment" request? Does the payment get sent again?
So what do you do? Fortunately we have the Post/Redirect/Get design pattern. The user submits a POST request to the server, the server redirects the user's browser to another page and that page is then retrieved using GET.
Here is a simple example using PHP:
if(!empty($_POST['username'] && !empty($_POST['password'])) {
$user = new User;
$user->login($_POST['username'], $_POST['password']);
if ($user->isLoggedIn()) {
header("Location: /admin/welcome.php");
exit;
}
else {
header("Location: /login.php?invalid_login");
}
}
Notice how in this example even when the password is incorrect, I am still redirecting back to the login form. To display an invalid login message to the user, just do something like:
if (isset($_GET['invalid_login'])) {
echo "Your username and password combination is invalid";
}
It has nothing to do with your form or the values in it. It gets fired by the browser to prevent the user from repeating the same request with the cached data. If you really need to enable the refreshing of the result page, you should redirect the user, either via PHP (header('Location:result.php');) or other server-side language you're using. Meta tag solution should work also to disable the resending on refresh.
After processing the POST page, redirect the user to the same page.
On
http://test.com/test.php
header('Location: http://test.com/test.php');
This will get rid of the box, as refreshing the page will not resubmit the data.
It seems you are looking for the Post/Redirect/Get pattern.
As another solution you may stop to use redirecting at all.
You may process and render the processing result at once with no POST confirmation alert. You should just manipulate the browser history object:
history.replaceState("", "", "/the/result/page")
See full or short answers
You could try using AJAX calls with jQuery. Like how youtube adds your comment without refreshing. This would remove the problem with refreshing overal.
You'd need to send the info necessary trough the ajax call.
I'll use the youtube comment as example.
$.ajax({
type: 'POST',
url: 'ajax/comment-on-video.php',
data: {
comment: $('#idOfInputField').val();
},
success: function(obj) {
if(obj === 'true') {
//Some code that recreates the inserted comment on the page.
}
}
});
You can now create the file comment-on-video.php and create something like this:
<?php
session_start();
if(isset($_POST['comment'])) {
$comment = mysqli_real_escape_string($db, $_POST['comment']);
//Given you are logged in and store the user id in the session.
$user = $_SESSION['user_id'];
$query = "INSERT INTO `comments` (`comment_text`, `user_id`) VALUES ($comment, $user);";
$result = mysqli_query($db, $query);
if($result) {
echo true;
exit();
}
}
echo false;
exit();
?>
I had a situation where I could not use any of the above answers. My case involved working with search page where users would get "confirm form resubmission" if the clicked back after navigating to any of the search results. I wrote the following javascript which worked around the issue. It isn't a great fix as it is a bit blinky, and it doesn't work on IE8 or earlier. Still, though this might be useful or interesting for someone dealing with this issue.
jQuery(document).ready(function () {
//feature test
if (!history)
return;
var searchBox = jQuery("#searchfield");
//This occurs when the user get here using the back button
if (history.state && history.state.searchTerm != null && history.state.searchTerm != "" && history.state.loaded != null && history.state.loaded == 0) {
searchBox.val(history.state.searchTerm);
//don't chain reloads
history.replaceState({ searchTerm: history.state.searchTerm, page: history.state.page, loaded: 1 }, "", document.URL);
//perform POST
document.getElementById("myForm").submit();
return;
}
//This occurs the first time the user hits this page.
history.replaceState({ searchTerm: searchBox.val(), page: pageNumber, loaded: 0 }, "", document.URL);
});
I found an unorthodox way to accomplish this.
Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.
Quick Answer
Use different methods to load the form and save/process form.
Example.
Login.php
Load login form at Login/index
Validate login at Login/validate
On Success
Redirect the user to User/dashboard
On failure
Redirect the user to login/index
i'm working at PHP application but i have a trouble, in fact when a user logged out and press after logging out the back button of the browser he can see the previous page as if the session has not been destroyed :(( i have tried all that i find here and on the web but it doesn't work :'(
Can I disable the back button?
http://blog.priyakant.com/2014/09/23/browser-back-button-prevent/
Summary:
Browser back button – Prevent displaying of previous pages after logout – Cookie based approach
Posted on September 23, 2014 by Priyakant Patel — Leave a comment
Prevent displaying of previous pages after logout
Client browser application caches page for performance reason. In this case when user clicks on back (browser back button) it shows previous page from cache.
Case 1 : User is still logged in.
it is OK to display content of previous page.
Case 2 : User is logged out.
Potentially next user can click on browser back button and can see content(s) of previous page(s).
This could be big problem in many applications. In financial application next user potential can see financial data. Or Medical / Patient related application this could be HIPAA violation and company can face big penalties.
So let’s get back to the point, How can solve this problem?
I am proposing HTTP Cookie based approach.
Steps:
Create HTTP Cookie from server side with sliding expiration. Which can be accessed from Client JavaScript (Note: Browser clears this Cookie upon expiration).
Clear this cookie upon logout
If you don’t find this Cookie, reload the page. In this case server re-authenticates page and if necessary it will redirect to the login page
That’s it, Done!
Here is my implementation using ASP.NET. Implementation will varies based on server technology but idea stays same.
(Server Side). Create HTTP Cookie from server side with sliding expiration
Response.SetCookie(new HttpCookie(“TimeoutCookieName”, "1") { Expires = DateTime.UtcNow.AddMinutes(10) });
//NOTE 10 == Session Timeout. This will be same as your application login session timeout.
(Server Side). Clear this cookie upon logout
Response.SetCookie(new HttpCookie(“TimeoutCookieName”, "1") { Expires = DateTime.UtcNow});
(Client Side) : (Following script must exists immediately after BODY tag)
window.preventBackButton = function () {
try {
if (document && (!document.cookie || document.cookie.indexOf('_tc=1') < 0)) {
window.document.body.style.display = 'none'; window.location = window.location;
}
} catch (e) { }
};
window.preventBackButton(); //Call immediately after body tag
Please find ASP.NET implementation as follow:
////C# Helper class - Start
using System;
using System.Web;
namespace MyHelpers {
public static class MyHtmlHelper {
public const string TimeoutCookieName = "_tc";
public static HtmlString PreventBackButtonScript(HttpResponseBase response) {
response.SetCookie(new HttpCookie(TimeoutCookieName, "1") { Expires = DateTime.UtcNow.AddMinutes(10) });
var clientScript = "window.-reventBackButton = function() {
try {
if(document && (!document.cookie || document.cookie.indexOf('" + TimeoutCookieName + "=1') < 0)) {
window.document.body.style.display='none'; window.location = window.location;
}
} catch(e) {}
};
window.preventBackButton();";
return new HtmlString(clientScript);
}
public static void SafeUnSetTimeoutCookie(this HttpResponseBase response) {
response.SetCookie(new HttpCookie(TimeoutCookieName, "0") { Expires = DateTime.UtcNow.AddYears(-5) });
}
}
}
////C# Helper class - End
//Shared\_Layout.cshtml
//Make sure not to include after logout OR login page
<html>
<body>
#MyHelpers.MyHtmlHelper.PreventBackButtonScript(Response)
.
.
<⁄body>
<⁄html>
You cannot disable the back button. If you can see the previously logged out user's page then your session checking script fails somewhere. Use a process script when you submit the logout form then redirect the currently logged out user to the main page (if applicable).
You can't. Browsers cache pages so they don't have to request it from a web server every time they load a page. When you hit the back button it loads the last page without asking the server.
It's probably more to do with the caching headers you're sending back on each page request. You have content that is only valid for a short time so you need to make sure you send headers back when you generate the page telling the browser not to cache it locally.
Example of disabling the page caching here http://www.w3schools.com/php/func_http_header.asp:
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
Are you clearing out the cache/session of the user? Even if they hit back I don't think it should keep them logged in if you clear their session on log out.
Edit: Prior to editing - by someone other than OP - this question asked if it is possible to disable the browser's back button. My original answer to that question is below. Also, I feel I need to clarify - the below approaches for essentially "breaking" the back button are not approaches I recommend or like. You should design your application to react sensibly when using basic browser features like the back button rather than try to prevent their use.
You cannot disable the back button on a user's browser. It's a fundamental feature of browsers which can't be overridden.
You can make it so that your application breaks (displays an error message, requiring the user to start over or re-submit a request) if the user goes back. It's a bad idea to do this, because it is really an admission that you didn't take the back button into account when you designed the application. Every application, even order forms, shopping carts etc, if designed correctly should be able to use the back button.
One approach I have seen for breaking on back button use is to pass a token on every URL within the application, and within every form. The token is regenerated on every page, and once the user loads a new page any tokens from previous pages are invalidated.
When the user loads a page, the page will only show if the correct token (which was given to all links/forms on the previous page) was passed to it.
The online banking application my bank provides is like this. If you use the back button at all, no more links will work and no more page reloads can be made - instead you see a notice telling you that you cannot go back, and you have to start over.
That said, I should remind you that making it so your application breaks when the user goes back is a bad idea and shows a poor application design.