25

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!!

CodeManiak
  • 1,903
  • 4
  • 19
  • 32
  • 2
    The back button... is for every one of us Web Programmer a pain in some place... – Goikiu Jan 03 '14 at 08:16
  • hahahaha that is so good to hear even though it doesn't answer my question. I thought it was just me :) – CodeManiak Jan 03 '14 at 08: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 Jan 03 '14 at 08:21
  • totally, which is why I have the php to handle that stuff but somehow it fails! – CodeManiak Jan 03 '14 at 08:24
  • if(!self.z){self.z=1; [].slice.call(document.links).filter(/./.test, RegExp(location))[0].click();} – dandavis Jan 03 '14 at 08:28
  • @dandavis tried that one, no luck. You wouldn't happen to work at build now would you? – CodeManiak Jan 03 '14 at 08:43
  • i should mention that your problem has nothing to do with php, it's all the history script you're using and it's shortcomings. if you decalre a var and hit back, the var is still there: the page never reloads and thus never re-pings php/apache. also, onload/ready/onbeforeunload doesn't refire when you hit back because the page doesn't actually load again. see https://developer.mozilla.org/en-US/docs/Web/API/Window.onpopstate. – dandavis Jan 03 '14 at 15:25

10 Answers10

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

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();}
}
Gopal
  • 861
  • 12
  • 18
  • 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 Jan 03 '14 at 08:22
  • 1
    Consider including a [`Pragma: no-cache`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32) for HTTP 1.0 compatibility if that is of concern. – zamnuts Jan 03 '14 at 08: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 Jan 03 '14 at 08: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 Jan 03 '14 at 08:29
  • I have tons of HTML not encapsulated by PHP. I'll work on that – CodeManiak Jan 03 '14 at 08:30
  • yes agreed with @zamnuts or try to work implement another soltuion..see edit – Gopal Jan 03 '14 at 08:31
  • I'll check it out. As an update I got the header includes working after encapsulating all the HTML in php echo's, but it didn't fix the back button issue. I'll test the other solution now. I seriously appreciate everyones help! Thank you all, I'd never get this site built without stackoverflows awesome community! – CodeManiak Jan 03 '14 at 08:32
  • @CodeManiak, it is OK if there is a lot of HTML, just make sure your header call is *before* all of that! :) – zamnuts Jan 03 '14 at 08:36
  • Appears as though the javascript solution works about 20% of the time, I think the logic is flawed. But I have seen it work so I'm going to pursue this solution – CodeManiak Jan 03 '14 at 08:42
  • 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 Oct 31 '15 at 08:20
  • ... So if the input's value is not empty/undefined, use it because the back button was pressed. On a page refresh it will always be empty/undefined, so we know we can instead use the fresh Javascript data written out from server-side. – i_a Oct 31 '15 at 08:28
  • It worked well but on Safari it refreshes constantly in an infinite loop! any suggestions? – Jack Nov 28 '15 at 18:32
  • Super answer! [Here](https://stackoverflow.com/a/49569914/1526703)'s a jquery version:` ` – Anupam Mar 30 '18 at 07:50
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

Community
  • 1
  • 1
sfscs
  • 515
  • 4
  • 8
  • 4
    My IDE was telling me this was deprecated and I had to use `window.performance.getEntriesByType('navigation')[0].type === "back_forward"` instead. – SeinopSys Jun 13 '18 at 00:43
  • @SeinopSys good to know! I dug a little deeper and that [method](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type) is part of [Navigation Timing Level 2](https://w3c.github.io/navigation-timing/#widl-PerformanceNavigationTiming-type) which is still a working draft, but will probably be the standard in the future. – sfscs Jun 18 '18 at 22:01
  • 1
    Yes, yes, a thousand times yes. Even supported by IE9. – UXCODA Dec 19 '18 at 02:47
  • Just checking back in two years later and the Navigation Timing Level 2 is still a working draft :/. Web moves soooo slow. – sfscs Sep 02 '19 at 02:16
17

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() 
}
};
Community
  • 1
  • 1
t0vana
  • 173
  • 1
  • 7
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();
        }
    };
Javan R.
  • 2,011
  • 1
  • 19
  • 16
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.

bummi
  • 27,123
  • 14
  • 62
  • 101
jahackbeth
  • 529
  • 8
  • 17
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;
        });
    });
});
reyaner
  • 2,799
  • 1
  • 12
  • 17
2

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

window.addEventListener('popstate', () => {
  location.reload();
}, false);
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Rohan Venapusala
  • 83
  • 1
  • 1
  • 5
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();
            }
    });

Bharanikumar
  • 25,457
  • 50
  • 131
  • 201
0

window.onbeforeunload = function() { redirect(window.history.back(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 Dec 20 '16 at 12:23
  • when page back button event is called (it override) we redirect to history current page – Agustin Gandara Feb 14 '17 at 18:59
-4

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.

Goikiu
  • 574
  • 3
  • 12