mozilla
您的搜尋結果

    window.onpopstate

    大綱

    一個事件 handler 給 popstate 事件在 window 上執行。

    A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.

    Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history.back() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document.

    Browsers tend to handle the popstate event differently on page load. Chrome and Safari always emit a popstate event on page load, but Firefox doesn't.

    語法

    window.onpopstate = funcRef;
    
    • funcRef 是一個 handler function

    popstate 事件

    以範例來說,一個 page 在 http://example.com/example.html 會產生出一個 alert,像下面的 code 所示:

    window.onpopstate = function(event) {
      alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
    };
    
    history.pushState({page: 1}, "title 1", "?page=1");
    history.pushState({page: 2}, "title 2", "?page=2");
    history.replaceState({page: 3}, "title 3", "?page=3");
    history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
    history.back(); // alerts "location: http://example.com/example.html, state: null
    history.go(2);  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}
    

    注意雖然原始的歷史紀錄(為 http://example.com/example.html)沒有 state 物件與他相關。一個 popstate 被觸發會繳活記錄在第二個 hitsory.back() 被呼叫。

    規格

    相關

    Document Tags and Contributors

    標籤: 
    Contributors to this page: ChiLiJung, khalid32
    最近更新: khalid32,
    隱藏側邊欄