2015-02-10 54 views
7

我使用pushState並基於當前頁面的history.state生成popstate事件的頁面視圖。忽略Safari的初始頁面加載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在後退/前進瀏覽器按鈕上激發彈出窗口。

我想忽略Safari上的初始加載popstate事件(理想情況下沒有setTimeout且沒有瀏覽器檢測)。

此外,該網站是鏈接的混合 - 一些將觸發pushState和一些將從服務器正常加載 - 所以如果用戶是十頁導航歷史記錄並點擊後退按鈕,歷史將有一個pushState頁面和非pushState頁面的混合。

回答

5

我已經解決了在變量中保存從window.history.state.order獲得的初始訂單值的問題。當觸發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() 
    } 
} 

希望這個幫助!

+0

嗨IllRepublica,我感謝您的回答,我認爲這讓我感到非常親近。我只是不確定你從哪裏抽取'window.history.state.order'?是從'history.pushState'嗎? – 2016-06-15 21:17:45

+0

IllRepublica正在自己的應用中定義它。 – Benjamin 2016-06-16 16:27:53

相關問題