Home  >  Article  >  WeChat Applet  >  Detailed explanation of page interceptor for WeChat applet development

Detailed explanation of page interceptor for WeChat applet development

黄舟
黄舟Original
2018-05-29 09:51:543887browse

This article mainly introduces the sample code of the page interceptor of the WeChat applet. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look

Scenario

  • The mini program has 52 pages, 13 of which do not require any identity , another 39 pages require system roles. For these 39 pages, if the WeChat user does not have a system role, it will jump to the login page.

  • Whether there is system role information that needs to be obtained through asynchronous requests.

Requirement Analysis & Implementation

To abstract the requirements, what is actually needed is a filter to access the mini program page Filter, pass those that meet the conditions, and perform other processing if they do not meet the conditions.

Children's shoes that have used PHP's laravel framework must immediately think of the laravel framework's http middleware:

HTTP middleware provides a convenient mechanism to filter incoming applications HTTP requests, for example, Laravel includes a middleware by default to verify user authentication. If the user is not authenticated, the middleware will direct the user to the login page. However, if the user is authenticated, the middleware will allow the request. Keep going further. Of course, in addition to authentication, middleware can also be used to perform a variety of tasks. CORS middleware is responsible for adding appropriate response headers to all responses that are about to leave the program. A logging middleware can record all incoming applications. program request.

What is worrying is that the WeChat applet does not provide a middleware mechanism for Page instances. So we can only start from the life cycle of the Page instance.

For onLoad, a page will only be called once; for onShow, it will be called once every time the page is opened (for example, the applet moves from the background to the foreground).

In the onLoad or onShow hook function, verify the user's identity. If passed, pull the data required for the page, otherwise jump to the login page.

//orderDetail.js
onShow: function () {
  let that = this;
  //身份校验
  service.identityCheck(() => {
     //跳转到登录页
     wx.redirectTo({
      url: "/pages/common/login/login"
     });
    }, () => {  
     //获取页面数据等等   
     that.getDetail(this.orderId);
     ...
    }
  );
 },

However, every page must be written like this. There is a lot of repeated code and it is also very intrusive. It is better to wrap it with a decorative function (the taller term is the decorator pattern):

//filter.js
function identityFilter(pageObj){
  if(pageObj.onShow){
    let _onShow = pageObj.onShow;
    pageObj.onShow = function(){
      service.identityCheck(()=>{
        //跳转到登录页
        wx.redirectTo({
          url: "/pages/common/login/login"
        });
      },()=>{
        //获取页面实例,防止this劫持
        let currentInstance = getPageInstance();
        _onShow.call(currentInstance);
      });
    }
  }
  return pageObj;
}

function getPageInstance(){
  var pages = getCurrentPages();
  return pages[pages.length - 1];
}

exports.identityFilter = identityFilter;

filter.js is used to provide filter methods, in addition to the existing user identity interception, subsequent If other interceptions are needed, they can be added to this file. Then, in the applet page code that requires user identity interception, just use filter.identityFilter to process it:

//orderDetail.js
let filter = require('filter.js');
Page(filter.identityFilter({
  ...
  onShow: function () {
    //获取页面数据等等
    this.getDetail(this.orderId);
    //...
  },
  ...
}));

Use Promise for optimization

In the above implementation, every time the page is accessed, the method of obtaining the user's identity will be executed (that is, service. identityCheck in the above code). In fact, it is not necessary, just get it once when the mini program is started. In other words, execute it in the onLaunch method of app.js.

When each mini program page is instantiated, an asynchronous method is generally executed to obtain the data required by the page. The key is that we need to ensure that the asynchronous method of the page must be executed after the asynchronous request to obtain the user identity.

There is no doubt that Promise is best at handling the execution sequence of asynchronous requests. Master, let’s go through the code quickly:

//app.js
App({
  onLaunch:function(){
    let p = new Promise(function(resolve,reject){
      service.identityCheck(resolve,reject);
    });
    this.globalData.promise = p; 
  },
  ...
  globalData: {
    promise:null,
  }  
});
//filter.js
const appData = getApp().globalData;
function identityFilter(pageObj){
  if(pageObj.onShow){
    let _onShow = pageObj.onShow;
    pageObj.onShow = function(){
      //改动点
      appData.promise.then(()=>{
        //跳转到登录页
        wx.redirectTo({
          url: "/pages/common/login/login"
        });
      },()=>{
        //获取页面实例,防止this劫持
        let currentInstance = getPageInstance();
        _onShow.call(currentInstance);
      });
    }
  }
  return pageObj;
}

Summary

basically implements the user identity interceptor of the mini program page, but compared to laravel’s http middle The software is still inferior:

  • needs to wrap one layer of code for each page.

  • Even if the user identity verification fails, the mini program will not block the rendering of the page. If the asynchronous method to obtain the user identity takes one minute to complete, the mini program page will still be displayed, and it will jump to the login page after one minute. You need to add logic yourself, for example, during this minute, the page displays blank content.

The above is the detailed content of Detailed explanation of page interceptor for WeChat applet development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn