26

I use .htaccess to route all of my traffic to a single index.php file. The code below to directs traffic, but for some reason it doesn't work with the back button. I don't know what to do to get the back button working. I've tried a variety of things and googled quite a bit and none of it has worked so I'm hoping someone here can help!

<?php
   if(isset($_GET['parameters'])) {
      if($_GET['parameters'] == "repair")
         include 'repair.html';
      else if($_GET['parameters'] == "training")
         include 'training.html';
      else if($_GET['parameters'] == "products")
         include 'products.html';
      else if($_GET['parameters'] == "about")
         include 'about.html';
      else if($_GET['parameters'] == "employees")
         include 'employees.html';
      else if($_GET['parameters'] == "training")
         include 'training.html';
      else if($_GET['parameters'] == "newaccount")
         include 'newaccount.html';
      else if($_GET['parameters'] == "contact")
         include 'contact.html';
      else if($_GET['parameters'] == "recommended")
         include 'recommended.html';
      else if($_GET['parameters'] == "careers")
         include 'careers.html';
      else
         include 'home.html';
   }
   else
      include 'home.html';
?>

So far I've tried and failed to use: window.onbeforeunload body onunload=""

There has got to be a way to onunload=location.reload() or something! Somehow has to know the syntax!!

7
  • 2
    The back button... is for every one of us Web Programmer a pain in some place...
    – Goikiu
    Commented Jan 3, 2014 at 8:16
  • hahahaha that is so good to hear even though it doesn't answer my question. I thought it was just me :)
    – CodeManiak
    Commented Jan 3, 2014 at 8:17
  • 1
    The problem is that when you press back, the browser shows the last url, but returns to the last actual page load. Any AJAX content is forgotten, so you'll have to reload it.
    – GolezTrol
    Commented Jan 3, 2014 at 8:21
  • totally, which is why I have the php to handle that stuff but somehow it fails!
    – CodeManiak
    Commented Jan 3, 2014 at 8:24
  • if(!self.z){self.z=1; [].slice.call(document.links).filter(/./.test, RegExp(location))[0].click();}
    – dandavis
    Commented Jan 3, 2014 at 8:28

10 Answers 10

44

Try this... not tested. I hope it will work for you.

Make a new php file. You can use the back and forward buttons and the number/timestamp on the page always updates.

<?php
header("Cache-Control: no-store, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo time();
?>
<a href="http://google.com">aaaaaaaaaaaaa</a>

Or

I found another solution:

The onload event should be fired when the user hits the back button. Elements not created via JavaScript will retain their values. I suggest keeping a backup of the data used in dynamically created element within an INPUT TYPE="hidden" set to display:none then onload using the value of the input to rebuild the dynamic elements to the way they were.

<input type="hidden" id="refreshed" value="no">
<script type="text/javascript">
onload=function(){
var e=document.getElementById("refreshed");
if(e.value=="no")e.value="yes";
else{e.value="no";location.reload();}
}
13
  • Ahh yes this is the third solution I tried but I kept getting some silly error I couldn't figure out about the page already being loaded. Where am I supposed to include these headers? When I tried including them above everything in my index.php file I still errored
    – CodeManiak
    Commented Jan 3, 2014 at 8:22
  • 1
    Consider including a Pragma: no-cache for HTTP 1.0 compatibility if that is of concern.
    – zamnuts
    Commented Jan 3, 2014 at 8:24
  • I get this error Cannot modify header information - headers already sent by...... I already googled and tried to figure out this error before I asked this question and failed to find the solution... so what do I do to fix it?
    – CodeManiak
    Commented Jan 3, 2014 at 8:27
  • 1
    @CodeManiak If PHP has already sent the body of a HTTP response, you cannot modify header information. Calling header should be done before any output is sent to the browser: check any file includes for echo/print statements, rogue whitespace and HTML not encapsulated by PHP.
    – zamnuts
    Commented Jan 3, 2014 at 8:29
  • 1
    +1 +1 +1 Wish I could vote up more this simple solution. A non-dynamically created input element given a value set by Javascript, retains its value when the back button is pressed!! Brilliant! So by setting the value of a hidden element, the last javascript state can be saved even though the javascript is reinitialized from scratch when the back button is pressed. Brilliant!!! +1 +1 +1
    – i_a
    Commented Oct 31, 2015 at 8:20
35

A more recent solution is using the The PerformanceNavigation interface:

if(!!window.performance && window.performance.navigation.type === 2) {
    console.log('Reloading');
    window.location.reload();
}

Where the value 2 means "The page was accessed by navigating into the history".

View browser support here: http://caniuse.com/#search=Navigation%20Timing%20API

Reload the site when reached via browsers back button

4
  • 4
    My IDE was telling me this was deprecated and I had to use window.performance.getEntriesByType('navigation')[0].type === "back_forward" instead.
    – SeinopSys
    Commented Jun 13, 2018 at 0:43
  • @SeinopSys good to know! I dug a little deeper and that method is part of Navigation Timing Level 2 which is still a working draft, but will probably be the standard in the future.
    – sfscs
    Commented Jun 18, 2018 at 22:01
  • 1
    Yes, yes, a thousand times yes. Even supported by IE9.
    – UXCODA
    Commented Dec 19, 2018 at 2:47
  • Just checking back in two years later and the Navigation Timing Level 2 is still a working draft :/. Web moves soooo slow.
    – sfscs
    Commented Sep 2, 2019 at 2:16
18

The hidden input solution wasn't working for me in Safari. The solution below works, and came from here.

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload() 
    }
};
0
12

I found two ways to handle this. Choose the best for your case. Solutions tested on Firefox 53 and Safari 10.1

  1. Detect if user is using the back/foreward button, then reload whole page

    if (!!window.performance && window.performance.navigation.type === 2) {
        // value 2 means "The page was accessed by navigating into the history"
        console.log('Reloading');
        window.location.reload(); // reload whole page
    }
    
  2. Reload whole page if page is cached.

    window.onpageshow = function (event) {
        if (event.persisted) {
            window.location.reload();
        }
    };
    
0
8

This simple solution posted here Force page refresh on back button 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.

2
  • it's work. Thanks a lot this solve my problem i am facing from so long and didn't find solution.
    – sadia
    Commented Nov 17, 2016 at 11:42
  • @bummi this solution is not working in IE, any idea any alternative solution?
    – sadia
    Commented Nov 17, 2016 at 11:45
2

did you try something like this? not tested...

$(document).ready(function(){
    $('.ajaxAnchor').on('click', function (event){ 
        event.preventDefault(); 
        var url = $(this).attr('href');
        $.get(url, function(data) {
            $('section.center').html(data);
            var shortened = url.substring(0,url.length - 5);
            window.location.hash = shortened;
        });
    });
});
0
2

You can use the following to refresh the page by clicking the back button:

window.addEventListener('popstate', () => {
  location.reload();
}, false);
1

First of all insert field in your code:

<input id="reloadValue" type="hidden" name="reloadValue" value="" />

then run jQuery:

<script type="text/javascript">
   jQuery(document).ready(function()
    {
            var d = new Date();
            d = d.getTime();
            if (jQuery('#reloadValue').val().length === 0)
            {
                    jQuery('#reloadValue').val(d);
                    jQuery('body').show();
            }
            else
            {
                    jQuery('#reloadValue').val('');
                    location.reload();
            }
    });

0

When page back button event is called (it override) we redirect to history current page:

<script>
    window.onbeforeunload = function() { redirect(window.history.back(1)); };
</script>
2
  • 1
    Please could you explain what this is doing? Because it looks like if you try to leave the page then it triggers a "back". So if I'm trying to navigate to another page, it'll override it?
    – Lee Oades
    Commented Dec 20, 2016 at 12:23
  • 1
    when page back button event is called (it override) we redirect to history current page Commented Feb 14, 2017 at 18:59
-5

Ahem u_u

As i've stated the back button is for every one of us a pain in some place... that said...

As long as you load the page normally it makes a lot of trouble... for a standard "site" it will not change that much... however i think you can make something like this

The user access everytime to your page .php that choose what to load. You can try to work a little with cache (to not cache page) and maybe expire date.

But the long term solution will be put a code on "onload" event to fetch the data trought Ajax, this way you can (with Javascript) run the code you want, and example refresh the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.