Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a reload of page in Chrome using Javascript [no cache]

Tags:

I need to reload a page using JavaScript and ensure that it does not pull from the browser cache but instead reloads the page from the server. [As elements of the page will have changed in the interim]

On IE and FF I found that the following code worked fine;

window.location.reload(true);

However it does not work on Chrome or Safari.

I tried the following, but also to no avail;

window.location.replace(location.href);
document.location.reload(true);
document.location.replace(location.href);

Is there a solution to this issue?

Findings

After looking into this I have found that this issue is HTTP Protocol handling;

  1. Chrome sends a request with Pragma: no-cache HTTP field
  2. Server responds with Last-Modified: DATE1 field
  3. JS uses location.reload(true) to force a reload from server not cache
  4. Chrome sends a request with If-Modified-Since: DATE1 field
  5. Server responds with HTTP Status 304 Not Modified

The server application is at fault for not noticing the state change in the dynamic page content, and thus not returning a 200. However, Chrome/WebKit is the only browser that sends a If-Modified-Since field when the JS location.reload(true) is called.

I thought I would put my findings here in-case someone else comes across the same issue.

like image 692
graney Avatar asked May 23 '12 12:05

graney


People also ask

How do I force Chrome to reload a page?

Chrome and Windows: To hard refresh on Google Chrome on Windows, there are two ways you can do it: Hold down Ctrl and click the Reload button. Or Hold down Ctrl and press F5.

How do you force refresh a page in JavaScript?

In JavaScript, you refresh the page using document. location. reload() . You can add the true keyword to force the reloaded page to come from the server (instead of cache).


3 Answers

You can use this hack:

 $.ajax({
        url: window.location.href,
        headers: {
            "Pragma": "no-cache",
            "Expires": -1,
            "Cache-Control": "no-cache"
        }
    }).done(function () {
        window.location.reload(true);
    });
like image 60
Suhan Avatar answered Sep 28 '22 10:09

Suhan


To ensure the page isn't loaded from cache you can add some unique number to query:

window.location = location.href + '?upd=' + 123456;

You also can use date instead of 123456

like image 32
m03geek Avatar answered Sep 28 '22 11:09

m03geek


Great findings! I just encountered the same issue and this really helps a lot! However, in addition to your finding, it seems that Chrome always sends a GET request for location.reload()...IE/FF is repeating the last request instead.

like image 25
Roy Ling Avatar answered Sep 28 '22 11:09

Roy Ling