問題描述:
在 iOS 系統中,用微信打開了 A 頁面的鏈接,然后由 A 頁面進入 B 頁面
在 B 頁面打開微信右上角菜單,使用“復制鏈接”功能
最后粘貼出來的鏈接是 A 頁面的鏈接
分析原因:
這個問題在微信 6.2 時代就已存在,GitHub 上有很多人到 weui 的主頁提 issue
https://github.com/Tencent/weui/issues/125
https://github.com/wuchangming/blog/issues/1
這兩個 issue 給了我很大的啟發
出現這個問題的原因,是因為微信內置瀏覽器對 history 的支持不夠全面
所以對於開啟了 History Mode 的 SPA 應用,只會保存第一條 url
只要每個頁面都刷新一次,嚴格的說不能是簡單的刷新,需要用 location.replace 刷新頁面,就能解決該問題
解決方案:
在使用了 vue-router 的項目中,添加路由守衛
在每次跳轉結束的時候,給 URL 添加一個隨機參數 wxr,然后執行 location.replace
當 URL 已經有了 wxr 這個參數,就直接加載頁面,避免無限刷新
function wxRefresh (to) { // 在鏈接后加一個隨機參數 wxr,以解決 ios 復制鏈接的問題
let wxr = 'wxr=' + new Date().getTime(); let url = location.protocol + '//' + location.host + '/page/im' + to.fullPath; if (location.search) { url = url + '&' + wxr; } else { url = url + '?' + wxr; } window.location.replace(url); } // 跳轉結束后校驗 wxr 參數
app.router.afterEach((to, from) => { !to.query.wxr && wxRefresh(to); });
另外,在頁面內需要將 url 還原為正常的地址
可以在 vuex 或者第三方 js 中添加一個公用方法
setCurrentUrl: () => { // 刪除 url 中手動添加的隨機數 wxr let url = location.href.replace(/&wxr=[0-9]{13}/g, ''); window.history.replaceState({}, document.title, url); }
然后在 mounted 或者 created 中調用這個方法就好了