javascriptpage-refresh

Force Reload a Page with Javascript (No Button)


I'm working on a site, and when an individual visits a certain page, I need the page to refresh.

I tried using location.reload() as well as the timeout function, but the page kept reloading. I just need to impose a limitation on the function to have one relaod.


Solution

  • If you need a page to perform a task on load, but also know whether or not it should perform that task based on a previous load, then what you're taking about is persisting information outside of the page.

    localStorage is a common approach. For example, consider the following:

    const hasReloaded = localStorage.getItem('hasReloaded') || false;
    if (!hasReloaded) {
      localStorage.setItem('hasReloaded', 'true');
      location.reload();
    }
    

    The first thing the code does is look for a value in localStorage. If the value doesn't exist, it defaults to false. So when hasReloaded is false, the if block executes. Within that block, write a value to localStorage and reload.

    The next time the page loads, when it checks the value again it finds it and the if block doesn't execute.