简体   繁体   中英

JavaScript hard refresh of current page

How can I force the web browser to do a hard refresh of the page via JavaScript?
Hard refresh means getting a fresh copy of the page AND refresh all the external resources (images, JavaScript, CSS, etc.).

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

window.location.href = window.location.href

I was working on django , but nothing was working so this bypass worked for me , it's forwarding to the next so whenever you just want to come back it's Hard refreshing the page ! it's maybe not the proper way but can solve the issue , try it out and let me know !

window.history.forward(1);

For angular users and as found here , you can do the following:

<form [action]="myAppURL" method="POST" #refreshForm></form>
import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  // ...
})
export class FooComponent {
  @ViewChild('refreshForm', { static: false }) refreshForm;

  forceReload() {
    this.refreshForm.nativeElement.submit();
  }
}

The reason why it worked was explained on this website: https://www.xspdf.com/resolution/52192666.html

You'll also find how the hard reload works for every framework and more in this article

explanation: Angular

Location: reload(), The Location.reload() method reloads the current URL, like the Refresh button. Using only location.reload(); is not a solution if you want to perform a force-reload (as done with eg Ctrl + F5) in order to reload all resources from the server and not from the browser cache. The solution to this issue is, to execute a POST request to the current location as this always makes the browser to reload everything.

Accepted answer above no longer does anything except just a normal reloading on mostly new version of web browsers today. I've tried on my recently updated Chrome all those, including location.reload(true)<\/code> , location.href = location.href<\/code> , and <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" \/><\/code> . None of them worked.

The only issue is when files inclusion is performed via script by plugins you have no control to modify it. Don't worry about source files flooding. When older files are unlinked it will be automatically garbage collected.

Changing the current URL with a search parameter will cause browsers to pass that same parameter to the server, which in other words, forces a refresh.

  const url = new URL(window.location.href);
  url.searchParams.set('reloadTime', Date.now().toString());
  window.location.href = url.toString();

Hard refresh of current page. Put this at end of <body> :

<script>

    var t = parseInt(Date.now() / 10000)

    function addQuery(tag) {
      const url = new URL(tag.href || tag.src);
      url.searchParams.set('r', t.toString());
      tag.href = url.toString();
    }

    function refresh() {
      var x = localStorage.getItem("t");
      localStorage.setItem("t", t);
      if (x != t) addQuery(window.location)
      else {
        var a = document.querySelectorAll("a")
        var n = a.length
        while(n--) addQuery(a[n])
      }
    }

    refresh()

</script>

It is a working code from my homepage that do a forced refresh for every visitor so that any update will show up without a cashing problem.

Extending to querySelectorAll("script, style, img, a") has a problem: The tags after querySelectorAll is not parsed and the script, style and img tags before querySelectorAll has already loaded or is loading. Only the a tags is not yet loaded.

The last time x a refresh is done is stored in localStorage. It is compared to the current time t to prevent a page refresh within 10 seconds. Assuming a parse not take more than 10 sec I managed to stop a page refresh loop. Here is how it works for the visitor:

The time x != t is true so the addQuery(window.location) will make a hard refresh of page because a query string is added.

Because the hard refresh will be within 10 seconds the next time x != t is false. In that case the addQuery is used to add query strings to href and src .

This is a 2022 update with 2 methods, considering SPA's with # in url:

METHOD 1:

As mentioned in other answers one solution would be to put a random parameter to query string. In javascript it could be achieved with this:

function urlWithRndQueryParam(url, paramName) {
    const ulrArr = url.split('#');
    const urlQry = ulrArr[0].split('?');
    const usp = new URLSearchParams(urlQry[1] || '');
    usp.set(paramName || '_z', `${Date.now()}`);
    urlQry[1] = usp.toString();
    ulrArr[0] = urlQry.join('?');
    return ulrArr.join('#');
}

function handleHardReload(url) {
    window.location.href = urlWithRndQueryParam(url);
    // This is to ensure reload with url's having '#'
    window.location.reload();
}

handleHardReload(window.location.href);

The bad part is that it changes the current url and sometimes, in clean url's, it could seem little bit ugly for users.

METHOD 2:

Taking the idea from https://splunktool.com/force-a-reload-of-page-in-chrome-using-javascript-no-cache , the process could be to get the url without cache first and then reload the page:

async function handleHardReload(url) {
    await fetch(url, {
        headers: {
            Pragma: 'no-cache',
            Expires: '-1',
            'Cache-Control': 'no-cache',
        },
    });
    window.location.href = url;
    // This is to ensure reload with url's having '#'
    window.location.reload();
}

handleHardReload(window.location.href);

Could be even combined with method 1, but I think that with headers should be enought:

async function handleHardReload(url) {
    const newUrl = urlWithRndQueryParam(url);
    await fetch(newUrl, {
        headers: {
            Pragma: 'no-cache',
            Expires: '-1',
            'Cache-Control': 'no-cache',
        },
    });
    window.location.href = url;
    // This is to ensure reload with url's having '#'
    window.location.reload();
}

handleHardReload(window.location.href);

The most reliable way I've found is to use a chache buster by adding a value to the querystring.

Here's a generic routine that I use:

    function reloadUrl() {

        // cache busting: Reliable but modifies URL
        var queryParams = new URLSearchParams(window.location.search);
        queryParams.set("lr", new Date().getTime());        
        var query = queryParams.toString();                
        window.location.search = query;  // navigates
    }

Calling this will produce something like this:

https://somesite.com/page?lr=1665958485293

after a reload.

This works to force reload every time, but the caveat is that the URL changes. In most applications this won't matter, but if the server relies on specific parameters this can cause potential side effects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM