可以使用 window.location.replace() 方法重定向到另一個頁面。相對於 window.location.href ,replace的優勢是不會跳轉記錄並不會保留在歷史會話中,這就是說用戶可以通過后退按鈕回到上一個正常頁面,而不是進入到無休止的回退→跳轉的流程。
下面是對使用JavaScript來進行跳轉的一些建議:
- 如果是想模擬用戶點擊鏈接進行跳轉,建議使用window.location.href
- 如果是想模擬HTTP重定向,建議使用window.location.replace()
// similar behavior as an HTTP redirect window.location.replace("http://stackoverflow.com"); // similar behavior as clicking on a link window.location.href = "http://stackoverflow.com";