忽略Safari的初始页面加载popstate

7
我正在使用pushState,并且根据当前页面的history.state在popstate事件上生成页面视图。
如果没有history.state,我希望重新加载文档。
window.onpopstate = function(event) {
    if( window.history.state !== null ){
        // page was ajax created and history created by pushState
        // recreate with ajax
    }
    else{
        // page was loaded from server normally
        document.location.reload()
    }
}

问题在于Safari会在初始页面加载时触发popstate事件。Chrome和Firefox在浏览器的后退/前进按钮上触发popstate事件。
我想忽略Safari上的初始加载popstate事件(最好不使用setTimeout和浏览器检测)。
此外,该网站是链接的混合体——有些链接将触发pushState,而有些链接将从服务器正常加载——因此,如果用户进行了十页的导航历史记录并单击“回退”按钮,则历史记录将包含pushState页面和非pushState页面。

关于Chrome中相同的bug问题,该浏览器也是基于Webkit的,有很多答案。顺便说一句,我在最近的Safari 11.1.2中没有看到这种行为。 - kolen
1个回答

5

我已经解决了一个问题,将从window.history.state.order获取的初始订单值保存在变量中。当触发on popstate事件时,之前存储的值会与当前订单值进行比较。如果它们相同,则不需要做任何事情(必须忽略Safari触发的初始popstate值)。下面是一个示例:

var initial_oder = window.history.state.order || 0;    
window.onpopstate = function(event) {
    if( window.history.state !== null && window.history.state.order !== initial_order){
        // page was ajax created and history created by pushState
        // recreate with ajax
    }
    else{
        // page was loaded from server normally
        document.location.reload()
    }
}

希望这能帮到你!

嘿,IllRepublica,感谢你的回答,我觉得它让我离成功非常接近了。只是我不确定你从哪里获取 window.history.state.order?是从 history.pushState 中获取的吗? - Rob Erskine
IllRepublica正在他们自己的应用程序中定义它。 - Benjamin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接