简体   繁体   中英

Force reload/refresh when pressing the back button

I will try my best to explain this.

I have an application that show the 50+ projects in my view page. The user can click the individual project and go to the update page to update the project information. Everything works fine except that after user finish updating the individual project information and hit 'back' button on the browser to the previous view page . The old project information (before update) is still there. The user has to hit refresh to see the updated information. It not that bad, but I wish to provide better user experience. Any idea to fix this? Thanks a lot.

I use these four lines of PHP code:

// any valid date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// always modified right now
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: private, no-store, max-age=0, no-cache, must-revalidate, post-check=0, pre-check=0");
// HTTP/1.0
header("Pragma: no-cache");

The key is using the "no-store" clause of the Cache-Control header.

The "fb-cache" can be really annoying. Here is a simple javascript way around it:

window.onpageshow = function(evt) {
    // If persisted then it is in the page cache, force a reload of the page.
    if (evt.persisted) {
        document.body.style.display = "none";
        location.reload();
    }
};

Tested in Safari 6 and IE10.

I think you must work with JS to make this work, since there is no way for PHP to know what browser controlls the user has access to...

Maybe this will help: http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

 if (window.name == "reloader") {
            window.name = "";
            location.reload();
        }

window.onbeforeunload = function() {
                window.name = "reloader"; 
            }

Add this two functions in every pages

None of the above solutions worked for me. This simple solution posted here worked ...

I've tried to force a page to be downloaded again by browser when user clicks back button, but nothing worked. I appears that modern browsers have separate cache for pages, which stores complete state of a page (including JavaScript generated DOM elements), so when users presses back button, previous page is shown instantly in state the user has left it. If you want to force browser to reload page on back button, add onunload="" to your (X)HTML body element:

<body onunload="">

This disables special cache and forces page reload when user presses back button. Think twice before you use it. Fact of needing such solution is a hint your site navigation concept is flawed.

Fortunately, we don't have to support browsers below IE10, so if you're willing or privileged enough to support only browsers that are HTML5 capable, the following should work:

/*
 * The following is intentional, to force Firefox to run 
 * this JS snippet after a history invoked back/forward navigation.
 */
window.onunload = function(){};    

function formatTime(t) {
    return t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds();
}

if (window.history.state != null && window.history.state.hasOwnProperty('historic')) {
    if (window.history.state.historic == true) {
        document.body.style.display = 'none';
        console.log('I was here before at ' + formatTime(window.history.state.last_visit));
        window.history.replaceState({historic: false}, '');
        window.location.reload();
    } else {
        console.log('I was forced to reload, but WELCOME BACK!');
        window.history.replaceState({
            historic  : true,
            last_visit: new Date()
        }, '');
    }
} else {
    console.log('This is my first visit to ' + window.location.pathname);
    window.history.replaceState({
        historic  : true,
        last_visit: new Date()
    }, '');
}

Well, here's the code without comments and flab:

window.onunload = function(){};

if (window.history.state != null && window.history.state.hasOwnProperty('historic')) {
    if (window.history.state.historic == true) {
        document.body.style.display = 'none';
        window.history.replaceState({historic: false}, '');
        window.location.reload();
    } else {
        window.history.replaceState({historic  : true}, '');
    }
} else {
    window.history.replaceState({historic  : true}, '');
}

Stick that just before your closing body tag, and you'll have a fairly clean solution.

This will work with any combination of back/forward being clicked, and the moment the user lands on a new page, no forced reloading will occur.

Read more about the History object on MDN:

MDN - The History Object

MDN - Manupulating the Browser History

This is the solution I have used:

<?php
session_start();
if (!$_SESSION['reloaded']) {$_SESSION['reloaded'] = time();}
else if ($_SESSION['reloaded'] && $_SESSION['reloaded'] == time()) { ?> 
<script> 
location.reload(); 
</script> 
<?php } ?>

after days of searching on the net to find a solution, i finally figure it out, add after:

<script>
 window.onbeforeunload = function(){window.location.reload();}
</script>

this will work like a charm you will thank me

this code will reload the page whenever you visit it.

好吧,您可以在更新页面上提供一个内置的后退按钮,将其发送到新的(例如链接<a href="<?= $_SERVER['HTTP_REFERRER']; ?>">BACK</a>或在页面上放置一些脚本,这会强制它在每次点击页面时提取数据,无论是新的印象,还是使用了后退按钮。

here's a solution that ive used in some of my pages. add this to pages that changes are made at.

window.onbeforeunload = function() {
     window.name = "reloader"; 
        }

this triggers when you leave those pages. you can also trigger it if there were changes made. so that it wont unnecessarily reload the page that needs reloading. then on pages that you want to get reloaded on after a the browser "back" use.

if (window.name == "reloader")
      {
        window.name = "no";
        reloadPage(); 
      }

this will trigger a reload on the page you need reloading to... hope this helps :) oh btw this is in js.

make a hidden checkbox and use below code(coffeescript)

window.location.reload()  if $("#refreshCheck")[0].checked
  $("#refreshCheck")[0].checked = true

I use a jquery and a php script to force reload on backbutton. The window.unload part is only needed in firefox. The outcommented timeout 1 second and body append part is only for illustration of functionality. window.location.reload(true) will give the same result as window.location.href = window.location.href;

jquery:

<script>
    $(window).unload(function() {});


        $.get('h.php',function(data){
            if($.trim(data)=='first'){
               // $('body').append(data)
               // setTimeout(function(){
               window.location.href = window.location.href;
               // },1000)
            }
            else {
                // $('body').append(data)
            }
        });

</script>

h.php:

<?php session_start(); ?>
<?php 
if(!$_SESSION['reloaded']){
    echo 'first';   

    $_SESSION['reloaded']=1;
}
else {
    echo 'second';
    unset($_SESSION['reloaded']);   
}
?>

You can send HTTP headers on your view page which tell the browser that the page cannot be cached. This means that the browser will need to request the page from the server every single time it is accessed - meaning it always show up to date information.

Headers need to be sent before any other content, so put the following right at the top of your view page.

header("Cache-Control: no-cache, must-revalidate");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM