History:replaceState() 方法
History 介面的 replaceState() 方法會修改當前歷史記錄條目,用方法引數中傳遞的 state 物件和 URL 替換它。當您想在響應某些使用者操作時更新當前歷史記錄條目的 state 物件或 URL 時,此方法特別有用。
語法
js
replaceState(state, unused)
replaceState(state, unused, url)
引數
返回值
無(undefined)。
異常
SecurityErrorDOMException-
如果關聯的文件未完全啟用,或者提供的
url引數不是有效 URL,或者方法呼叫過於頻繁,則會丟擲此異常。 DataCloneErrorDOMException-
如果提供的
state引數不可序列化,則會丟擲此異常。
示例
假設 https://www.mozilla.org/foo.html 執行了以下 JavaScript
js
const stateObj = { foo: "bar" };
history.pushState(stateObj, "", "bar.html");
在下一個頁面上,您可以使用 history.state 來訪問剛剛新增的 stateObj。
上述這兩行的解釋可以在 Working with the History API 文章中找到。然後假設 https://www.mozilla.org/bar.html 執行了以下 JavaScript
js
history.replaceState(stateObj, "", "bar2.html");
這將導致 URL 欄顯示 https://www.mozilla.org/bar2.html,但瀏覽器不會載入 bar2.html,甚至不會檢查 bar2.html 是否存在。
現在假設使用者導航到 https://www.microsoft.com,然後點選“後退”按鈕。此時,URL 欄將顯示 https://www.mozilla.org/bar2.html。如果使用者現在再次點選“後退”,URL 欄將顯示 https://www.mozilla.org/foo.html,並完全跳過 bar.html。
規範
| 規範 |
|---|
| HTML # dom-history-replacestate-dev |
瀏覽器相容性
載入中…