最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Refresh page ONCE - Stack Overflow

programmeradmin1浏览0评论

I would like to implement a JavaScript code which states this: if the page is loaded pletely, refresh the page immediately, but only once. This one works fine:

window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
} 

but I don't want hash at the end. Any solution?

I would like to implement a JavaScript code which states this: if the page is loaded pletely, refresh the page immediately, but only once. This one works fine:

window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
} 

but I don't want hash at the end. Any solution?

Share Improve this question edited Mar 6, 2022 at 19:02 Progman 19.7k7 gold badges55 silver badges82 bronze badges asked Mar 6, 2022 at 18:25 Mateusz KalinowskiMateusz Kalinowski 311 silver badge3 bronze badges 1
  • 1 Why? There might be a better solution to your problem – Daniel A. White Commented Mar 6, 2022 at 19:36
Add a ment  | 

2 Answers 2

Reset to default 3

use cookies or localStorage

window.onload = function() {
    if(!localStorage.loaded) {
        localStorage.setItem('loaded', 'yes')
        window.location.reload();
    }
} 

If first time will loaded then you have to set the hash ('loaded'). The automatically will reload the page. Second time he will found the hash #loaded in the url and dont reload the page again.

To avoid hash in the url you can use cookie or localStorage.

LocalStorage: In this case take a look to the answer from @uingtea: https://stackoverflow./a/71373469/14807111.

window.onload = function() {  
  if(window.location.hash !== '#loaded') {            
    window.location.hash = '#loaded';
    window.location.reload();
  }
} 

With cookie

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}


function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}



window.onload = function() {  
  if(getCookie('loaded')) {            
    setCookie('loaded','true',180);
    window.location.reload();
  }
}

发布评论

评论列表(0)

  1. 暂无评论