


Detailed explanation of page interceptor for WeChat applet development
May 29, 2018 am 09:51 AMThis 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; //身份校驗(yàn) service.identityCheck(() => { //跳轉(zhuǎn)到登錄頁 wx.redirectTo({ url: "/pages/common/login/login" }); }, () => { //獲取頁面數(shù)據(jù)等等 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(()=>{ //跳轉(zhuǎn)到登錄頁 wx.redirectTo({ url: "/pages/common/login/login" }); },()=>{ //獲取頁面實(shí)例,防止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 () { //獲取頁面數(shù)據(jù)等等 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(){ //改動(dòng)點(diǎn) appData.promise.then(()=>{ //跳轉(zhuǎn)到登錄頁 wx.redirectTo({ url: "/pages/common/login/login" }); },()=>{ //獲取頁面實(shí)例,防止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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Numpy is a Python scientific computing library that provides a wealth of array operation functions and tools. When upgrading the Numpy version, you need to query the current version to ensure compatibility. This article will introduce the method of Numpy version query in detail and provide specific code examples. Method 1: Use Python code to query the Numpy version. You can easily query the Numpy version using Python code. The following is the implementation method and sample code: importnumpyasnpprint(np

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions
