微信瀏覽器對單頁面應用程序並不友好,在不使用微信 SDK 的狀況下沒法分享當前頁面,只能分享落地頁。html
個人博客文章:https://blog.ci0n.cn/p_ec7b781c.htmlvue
const UA = navigator.userAgent.toLowerCase() // 判斷微信瀏覽器 export const WECHAT_BROWSER = UA.includes('micromessenger')
import { WECHAT_BROWSER } from "./utils/browser.js" export default { name: "App", watch: { $route: { immediate: true, deep: true, handler(to, from) { if (!WECHAT_BROWSER) return; // 不會刷新瀏覽器,只是讓微信瀏覽器同步當前url // eslint-disable-next-line window.location.href = window.location.href } } } };
同步 url 以後是解決了問題,可是發現會出現一個奇怪的 bug。
在真機裏進入 http://192.168.1.5:8080
和 http://192.168.1.5:8080/#/
(兩個url的區別只在/#/
),會發現其中一個連接依然沒法分享當前頁面。瀏覽器
import { WECHAT_BROWSER } from "./utils/browser.js"; if (WECHAT_BROWSER && window.location.search.includes('from_wx') === false) { let url = window.location.href url += (location.search ? '&' : '?') + 'from_wx=1' window.location.replace(url) } new Vue({ // ... })
使用一個標誌位在 vue 執行以前(爲了儘快刷新頁面,節省等待的時間)判斷首次進入刷新頁面,這樣就能夠解決這個奇怪的 bug,可是會讓用戶等待的時間更長,影響了性能。微信
demoapp