的位置.用url片段替换不一致的部分

location.replace inconsistencies with url fragments

本文关键字:不一致 替换 片段 位置 url      更新时间:2023-09-26

我最近注意到location.replace实际上并没有重新加载页面,当有一个url片段(#)在当前url和目标url:

// Assume the current url is /#url-fragment
window.location.replace('/#my-new-url-fragment');
// Doesn't reload the page.

我正在寻找一个可靠的,跨浏览器的方式(支持IE8),以取代当前的url,而不添加到历史记录

这是我能做到的最好的答案,但它不是一个非常全面的答案。这更多的是一种试错,而不是真正的合理化行为。

我建立了一个所有可能场景的表,然后一个脚本来检查结果。在所有条件下都有效的逻辑是:

window.location.replace(url);
/* If the target url has a hash, and ignoring hashes the two urls match,
   then the location.replace() call above *did not reload the page*. Do so now. */
var urlWithoutHash = ...; // /test#hash -> /test
var currentUrlWithoutHash = ...;
if (url.indexOf('#') >= 0 && urlWithoutHash == currentUrlWithoutHash)
    window.location.reload();