在微信中使用一個SPA應用時,複製當前鏈接、分享好友或者朋友圈、以及在瀏覽器中打開,鏈接始終是初始進入的路由。
舉個例子:
你在微信中點擊進入了一個SPA單頁面:
www.baidu.com/main
當你做了一系列操作,路由跳轉到了:
www.baidu.com/detail
這時點擊右上角,
無論是複製鏈接,分享給好友還是朋友圈,或者在瀏覽器中打開,url始終是www.baidu.com/main。
不要慌,你的頁面沒有毛病,這是因爲微信瀏覽器對histroy的支持還還全面,只保存了第一條history記錄。
有兩個解決方案:
- 使用微信的jssdk,可以配置分享好友和朋友圈的鏈接,但是複製鏈接和瀏覽器中打開不行;
- 可以使用history.replace,替換微信瀏覽器僅存的一條histroy記錄爲當前路由;
/**
* 在微信瀏覽器內只保存一條history記錄,使用history.replace替換成當前路由
* 增加一個標誌參數,這樣可以避免重複replace
*/
const wxRefresh = () => {
const PARAM_NAME = 'wxReplaceTime'; // 新增的參數名
const { protocol, host, pathname, hash, search } = window.location;
if ( search.indexOf(PARAM_NAME) > -1 ) return; // 避免重複刷新,參數已存在
const replaceQueryParam = ( paramName, newVale ) => {
const reg = new RegExp(`([?;&])${paramName}[^&;]*[;&]?`);
const query = search.replace(reg, '$1').replace(/&$/, '');
return (query.length > 2 ? `${query}&` : '?') + (newVale ? `${paramName}=${newVale}` : '');
};
window.location.replace(
`${protocol}//${host}${pathname}${replaceQueryParam(PARAM_NAME, new Date().getTime())}${hash}`
);
};