background

The whole content of the applets is embedded in H5 using web-view components. However, such a small program login state can not be saved for a long time; After a short period of time or after closing the APP process to which the small program belongs, the user will log in again next time after entering the small program, which is not good user experience. Therefore, the following solution is provided.

The solution

H5 sends token to applets -> Applets receive token and there is local cache -> Next time open applets, get token from local cache, and spliceit to SRC of web-view component -> H5 intercepts token and sets login state

Uni-app framework adopted by applets; H5 is the Nuxt framework.

H5

  1. In nuxt. Config. Introducing Uni – App JSSDK js file (js.cdn.aliyun.dcloud.net.cn/dev/uni-app…
Head: {script: [] {SRC: 'https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.0.1.52.js'}}Copy the code

2. After the login is successful, send messages to the application

if(isMiniWechat) {
    uni.postMessage({
      data: {
        token: token
      }
    })
}
Copy the code

3. Block tokens in urls

app.router.beforeEach((to, from, next) => {
    if (to.query.token && isMiniWechat) {
      store.commit('SET_TOKEN', to.query.token)
    }
})
Copy the code

Environmental judgment – wechat small program

function isMiniWechat (UA) {
  return /miniProgram/i.test(UA) && /micromessenger/i.test(UA)
}
Copy the code

Small program

1. Web-view component receives the message sent by H5; The token is obtained and stored in the local cache

< web - view the SRC = "h5 link" @ message = "bindmessage" > < / web - view > bindmessage (e) {const data = e.d etail. Data | | if [] (data.length) { const nuxtToken = data.find(item => item.token) nuxtToken && uni.setStorageSync('nuxt_token', nuxtToken); }}Copy the code

2. Pass the token through the URL before setting the SRC of the Web-view component

const token = uni.getStorageSync('nuxt_token'); If (token) {this.url = 'h5 link? Token =${token} '} else {this.url = h5 link}Copy the code