How to force a page to reload if all what was changed in url is hash?

家住魔仙堡 提交于 2019-11-28 19:08:12

Remove the anchor you're going to navigate to, then use approach #2? Since there's no anchor, setting the hash shouldn't scroll the page.

I had a JQuery function that fired on $(document).ready() which detected if there was a hash appended to the URL in my case, so I kept that function the same and then just used a force reload whenever a hash change was detected:

$(window).on('hashchange',function(){ 
    window.location.reload(true); 
});

Then my other function -

$(document).ready(function() {
    var hash = window.location.hash;    
    if(hash) {
           //DO STUFF I WANT TO DO WITH HASHES
    }
});

In my case, it was fine for UX -- might not be good for others.

It should be expected that #foo will scroll to the anchor of the id, "foo". If you want to use approach #1 and have it reload, this approach might work.

if (Object.defineProperty && Object.getOwnPropertyDescriptor) { // ES5
    var hashDescriptor = Object.getOwnPropertyDescriptor(location, "hash"),
    hashSetter = hashDescriptor.set;
    hashDescriptor.set = function (hash) {
        hashSetter.call(location, hash);
        location.reload(true);
    };
    Object.defineProperty(location, "hash", hashDescriptor);
} else if (location.__lookupSetter__ && location.__defineSetter__) { // JS
    var hashSetter = location.__lookupSetter__("hash");
    location.__defineSetter__("hash", function (hash) {
        hashSetter.call(location, hash);
        location.reload(true)
    });
}

Another option is to remove the hash and store it in session storage to be retrieved on reload:

var newUrl = location.href + '#myHash';
var splitUrl = newUrl.split('#');
newUrl = splitUrl[0];
if (splitUrl[1]){
    sessionStorage.savedHash = splitUrl[1];
}
location.href = newUrl;

and then on top of your page you can have the following code:

var savedHash = sessionStorage.savedHash;
if (savedHash){
    delete sessionStorage.savedHash;
    location.hash = savedHash;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!