最近有個小H5項目 是通過微信小程序進的 因流程較長所以想在最后的訂單詳情頁面點返回按鈕時 回到首頁
本打算頁面跳轉都用location.replace 但中間有幾步操作希望能用返回返到上個頁面 因此無法使用replace
此外想着能不能在最后一個頁面能否清掉瀏覽器歷史記錄 發現沒有相關方法
最后發現可以監聽返回事件 最后用了這個方式
mdn 相關介紹
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/popstate_event
假設想要點擊返回的頁面是/xxx/detail.html
使用發現 想要注冊的popstate回調函數起作用 需要歷史記錄是通過pushstate推進去的
因此需要先向history中推入一條記錄 並監聽popstate事件
window.history.pushState({ url:'index.html' }, "index", '0');
window.addEventListener("popstate", function (e) {
console.log(e.state,'e.state')
});
此時會發現瀏覽器的url欄 變成了/xxx/0 但是頁面並沒有發生跳轉
應該是只在瀏覽器歷史棧中push了一條0的記錄 但是不會觸發頁面跳轉之類
此時控制台調用history.back() 發現打印的不是預期的{ url:'index.html' } 這個傳的state 說明popstate傳入的e應該是要返回的那個頁面的state
新增的0頁面的上個頁面是/xxx/detail.html 此頁面是無history.state值的
要想獲取到state值 我這邊是再次新增一條記錄
window.history.pushState({ url:'', flag:'1' }, "index", '1');
此時發現 頁面返回可以打印出{ url:'index.html' } 這個history.state 就可以進行想要的效果了
最終代碼
// 向history推一條記錄 為了用 {url:'index.html?needClose=1' }這個state
window.history.pushState({ url:'index.html?needClose=1' }, "index", '');
window.history.pushState({ url:'' }, "index", '');
// 定時器 剛進頁面瀏覽器會自動push一條本頁面歷史記錄 防止沖突
setTimeout( () => {
window.addEventListener("popstate", function (e) {
// state有值則跳轉
if (e.state != null && e.state.url != '') {
location.href = e.state.url
}
});
},300 )
此時在手機detail頁面點返回便可以返回到首頁了
但是這時首頁點返回就返回到detail頁面了。。
所以首頁也要改下。
獲取query中參數
if( needClose ){
setTimeout( () => {
// 向history推一條記錄 不然popstate事件無法觸發
window.history.pushState({ url:'', }, "index", '');
window.addEventListener("popstate", function (e) {
// 調用小程序api 關閉所有頁面 並跳到小程序首頁
wx.miniProgram.reLaunch({url: '/xxxxxx/xxxx})
});
},800 )
}