John Doeherskij
John Doeherskij

Reputation: 2577

How to force reloading a page when using browser back button?

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:

  1. user is visiting page1.
  2. while on page1 - he clicks on a link to page2.
  3. he is redirected to the page2
  4. now (Important part!) he clicks on the back button in browser because he wants to go back to page1
  5. he is back on the page1 - and now the page1 is being reloaded and something is alerted like "You are back!"

Upvotes: 205

Views: 274832

Answers (20)

Jiao
Jiao

Reputation: 121

// refresh it window.addEventListener('pageshow', function (event) { if (event.persisted || performance.getEntriesByType("navigation")[0].type === "back_forward") { // Check if the page was loaded from the cache or via back/forward navigation window.location.reload(); // Force a reload } }); This works for me

Upvotes: 0

crag
crag

Reputation: 399

Along with these JS solutions listed above:

To get Chrome to use the 'back_forward' navigation type, set the page cache to 'no-store'. This was using Chrome Version 126.0.6478.185.

My use case was for web forms; Which looked like adding 'Response.Cache.SetNoStore()' to the Page_Load method.

I do not know why this works. I stumbled into it when reviewing this article from Google for their backward/forward cache service. https://developer.chrome.com/docs/devtools/application/back-forward-cache/

Upvotes: 0

sipi09
sipi09

Reputation: 537

I tried all the solutions from the previous answers. None worked.

Finally I found this solution, which did work:

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

Upvotes: 20

imjoymhnt
imjoymhnt

Reputation: 1091

I recently faced the same kind of issue in one of my React applications.

Whenever you're clicking on the button to visit page 2 if you're using the history.push(url) method inside that visit page 2 button function, and then clicking on the browser back button will change the URL only, but it'll not reload that page.

To reload the page while clicking on the back button, you can use window.location.assign(url) method inside that visit page 2 button function.

example:

import {useHistory} from 'react-router-dom'

const App = () => {

const history = useHistory()

const handleClick = () => {
  // history.push('/page-2-url') // Don't use this
  window.location.assign('/page-2-url') // use this
}

  return <div>
    <button onClick={handleClick}>Go to Page 2</button>
  </div>
}

export default App;

Upvotes: 0

Mike Godin
Mike Godin

Reputation: 3937

Here's a version that seems to work in older and newer mobile and desktop browsers:

window.addEventListener("pageshow", function (event) {
  var historyTraversal = event.persisted,
    perf = window.performance,
    perfEntries =
      perf && perf.getEntriesByType && perf.getEntriesByType("navigation"),
    perfEntryType = perfEntries && perfEntries[0] && perfEntries[0].type,
    navigationType = perf && perf.navigation && perf.navigation.type;
  if (
    historyTraversal ||
    perfEntryType === "back_forward" ||
    navigationType === 2 
  ) {
    // Handle page restore.
    window.location.reload();
  }
});

Upvotes: 3

Francesco
Francesco

Reputation: 589

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.

Upvotes: 38

luthier
luthier

Reputation: 2841

Since performance.navigation is now deprecated, you can try this:

var perfEntries = performance.getEntriesByType("navigation");

if (perfEntries[0].type === "back_forward") {
    location.reload();
}

Upvotes: 55

paulo77
paulo77

Reputation: 174

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

Upvotes: 1

Lionia Vasilev
Lionia Vasilev

Reputation: 12748

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:

Upvotes: 174

ntc2
ntc2

Reputation: 11912

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.

Upvotes: 4

Andi
Andi

Reputation: 45

In Chrome 96 perfEntries[0].type is 'reload', when you use the back button

Upvotes: 0

Andi
Andi

Reputation: 45

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

Upvotes: 3

Panu Logic
Panu Logic

Reputation: 2263

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.

Upvotes: 1

Lotok
Lotok

Reputation: 4607

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

Upvotes: 84

kvothe__
kvothe__

Reputation: 661

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

Upvotes: 9

Rajesh Kharatmol
Rajesh Kharatmol

Reputation: 141

Use following meta tag in your html header file, This works for me.

<meta http-equiv="Pragma" content="no-cache">

Upvotes: 0

Marlon
Marlon

Reputation: 1877

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

Upvotes: 15

muhammed aslam
muhammed aslam

Reputation: 44

I found the best answer and it is working perfectly for me

just use this simple script in your link

<A HREF="javascript:history.go(0)">next page</A>

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

Upvotes: -1

Dhiraj
Dhiraj

Reputation: 1462

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.

Upvotes: 7

Anton Stepanenkov
Anton Stepanenkov

Reputation: 1036

Reload is easy. You should use:

location.reload(true);

And detecting back is :

window.history.pushState('', null, './');
  $(window).on('popstate', function() {
   location.reload(true);
});

Upvotes: 1

Related Questions