微信浏览器对单页面应用程序并不友好,在不使用微信 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