[javascript] How to refresh page on back button click?

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

This question is related to javascript php jquery ajax .htaccess

The answer is


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


window.onbeforeunload = function() { redirect(window.history.back(1)); };

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;
        });
    });
});

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.


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

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

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.


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();
            }
    });


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();
        }
    };

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() 
}
};

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to .htaccess

Use .htaccess to redirect HTTP to HTTPs Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04 Server unable to read htaccess file, denying access to be safe Laravel 5 – Remove Public from URL Laravel 5 not finding css files How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue? How Can I Remove “public/index.php” in the URL Generated Laravel? Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error Forbidden You don't have permission to access / on this server Htaccess: add/remove trailing slash from URL