vue3 + web微信登录

前段时间接触到了web上微信登录
原以为微信提供的sdk会很容易
最大的bug就是 引入js后 登录后不跳转
才知道浏览器的安全机制就是不让你随便跳
然后一通百度 才知道设置sanbox的属性可以绕过这个机制
然后找到一个不修改js源码 也可以实现的方法

将预留给微信二维码的div 设置为iframe
sandbox的三个属性是关键
<iframe id="wx_login_container" sandbox="allow-scripts allow-same-origin allow-top-navigation" />
js
const initWxLogin = () => {
    await new Promise((resolve, reject) => {
        // @ts-ignore
        if (typeof WxLogin !== 'undefined') return resolve()

        const script = document.createElement('script')
        script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js?t=' + Date.now()
        script.onload = () => resolve()
        script.onerror = (err) => reject(err)
        document.body.appendChild(script)
    })
    const iframe = document.getElementById('wx_login_container') as HTMLIFrameElement
    if (iframe) {
        // 清空iframe内容
        iframe.src = ''

        // 构建微信登录URL
        const wxLoginUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=xxx&redirect_uri=${encodeURIComponent('https://')}&response_type=code&scope=snsapi_login&state=xxx&self_redirect=false`
        // 设置iframe的src
        iframe.src = wxLoginUrl
        // 添加样式
        const style = document.createElement('style')
        style.textContent = `
      .impowerBox .qrcode { width: 260px !important; margin-top: 20px }
      .wrp_code { padding: 0 !important }`
        iframe.contentDocument?.head.appendChild(style)
    }
}
// 监听路由  登陆成功后 js会重定向到你的redirectUrl 并且携带着参数
watch(
  () => useRoute().route.query,
  () => {  // 获取query.code + 你的登录逻辑 }
)

大功告成
tips: 这个只能在正式环境测试 想在测试环境测试 需要去微信后台添加域名哦

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容