electron之微信扫码登陆(不使用轮询)

先说先思路:在要扫码的页面嵌入webview,注意这个webview是隐藏在页面的后面,里面是微信的扫码登陆界面,获取这个页面的二维码,然后把这个码显示到真实的页面上,用户扫码之后在webview里面的页面就会触发微信的回调,监听这个回调,获取自家服务器返回的信息,判断用户是否能够登陆

1. 嵌入webview

<webview id="webview" :src="wxloginurl"></webview>

2. 生成微信的扫码页面,就是上面wxloginurl

const appID = config.appID
const webviewUrl = encodeURIComponent(`${config.baseUrl}/login/weixin/callback`)
const state = Math.random().toString().slice(2)
this.wxloginurl = `https://open.weixin.qq.com/connect/qrconnect?appid=${appID}&redirect_uri=${webviewUrl}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`

3. 获取webview中的微信二维码

先引入能生成二维码的npm包  yarn add qrcode 

然后引入 import QRCode from 'qrcode'

const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', e => {
  webview.executeJavaScript(`document.querySelector('.qrcode').outerHTML`).then(res => {
    const uuid = res?.match(/src="\/connect\/qrcode\/(\S*)">/)[1]
    const qrCodeUrl = `https://open.weixin.qq.com/connect/confirm?uuid=${uuid}&chInfo=ch_share__chsub_CopyLink`
    QRCode.toDataURL(qrCodeUrl, (err, url) => {
       if (err) return
       // 这里的url就是要显示在真实页面上的二维码了
    })
  })
})

4. 用户扫码之后, 监听webview中地址的跳转,也就是微信的回调

webview.addEventListener('will-navigate', (e) => {
  const webContents = this.$electron.remote.webContents.fromId(webview.getWebContentsId())
  // 过滤url地址,只监听需要的url
  const filter = { urls: [`${config.baseUrl}/*`] }
  webContents.session.webRequest.onCompleted(filter, (details) => {
     const Token = details.responseHeaders['Header-Access-Token']
     // 我这里是获取到请求头中的Token,details中有更多信息
     // do some thing 
  })
})

还有一种简单的方法:

就是直接通过 this.$electron.remote.session.defaultSession.webRequest.onCompleted(filter, (details) => {}) 监听扫码后微信的回调

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值