


Understand the automatic tracking points of WeChat mini program Taro
Related learning recommendations: Small Program Development Tutorial
When doing various businesses, we cannot To avoid the need to bury points in the business, these burying points usually include but are not limited to exposure, clicks, dwell time, leaving the page and other scenarios. In the mini program, due to its different architecture from the browser, the monitoring page has changed. It is more difficult. Usually we will rewrite the Page
method to intercept the proxy for the native life cycle of the mini program, so as to bury the business, but in Taro
everything becomes different. .
Current situation
In multi-end unified Taro
, we can no longer see explicit Page
calls, or even Taro
There is no longer any sign of Page
in the packaged code, instead it is the native Component
of the mini program (you can know this by observing the packaged content ), so in order to realize the automatic embedding of WeChat applet in Taro
, we need to change a strategy: rewrite Component
.
Basic rewriting
In the WeChat applet, the exposed Component
and Page
can be directly rewritten and assigned:
const _originalComponent = Component;const wrappedComponent = function (options) { ...do something before real Component return _originalComponent(options); }复制代码
This can solve the problem quickly, but when we do this in another small program, we need to do these processes manually again, which is inevitably a bit troublesome. Why not find a more general one? Plan, we only need to focus on the business we need to pay attention to (buried points)?
Solution
The most important thing is to think from scratch, grasp the real problem, and get close to the essence of the problem
Root problem
Before solving the problem, let us first take a look at the essence of the problem. If you want to automatically bury points in a mini program, what you actually need to do is to do some fixed processing in the life cycle specified by the mini program. Therefore, our problem of automatic burying is actually how to hijack the life cycle of the mini program. To hijack the life cycle of the applet, all we need to do is to rewrite options
.
How to solve
Before solving this problem, we have to separate the problems we need to solve:
- How to rewrite
options
- Which
options should be rewritten
- How to inject your own business into the listening life cycle.
Our basic solution above already has the answer to how to rewrite options
. We only need to wrap another layer outside the method provided by the original applet to solve the problem. , and in order to ensure that our solution can be applied to native mini programs and multi-terminal unified mini program solutions such as Taro
, we should also support rewriting Component
and Page
, and for the last question, we can think about the event system in js
. Similarly, we can also implement a set of publish and subscribe logic. We only need to customize the trigger event (life cycle) and listeners
, and then wrap the original logic of the life cycle;
step 1
First we are rewriting Component
and Page
The original method should be saved before to avoid the original method being contaminated and we cannot roll back. After that, we can enumerate all the life cycles in the applet and generate a default event object to ensure that we have registered the corresponding life cycle. The listeners
can be found through addressing and the original life cycle method can be rewritten.
export const ProxyLifecycle = { ON_READY: 'onReady', ON_SHOW: 'onShow', ON_HIDE: 'onHide', ON_LOAD: 'onLoad', ON_UNLOAD: 'onUnload', CREATED: 'created', ATTACHED: 'attached', READY: 'ready', MOVED: 'moved', DETACHED: 'detached', SHOW: 'show', HIDE: 'hide', RESIZE: 'resize', };public constructor() { this.initLifecycleHooks(); this.wechatOriginalPage = getWxPage(); this.wechatOriginalComponent = getWxComponent(); }// 初始化所有生命周期的钩子函数private initLifecycleHooks(): void { this.lifecycleHooks = Object.keys(ProxyLifecycle).reduce((res, cur: keyof typeof ProxyLifecycle) => { res[ProxyLifecycle[cur]] = [] as WeappLifecycleHook[]; return res; }, {} as Record<string, WeappLifecycleHook[]>); }复制代码
step 2
In this step we only need to put the listening function into the event object we declared in the first step, and then execute the rewriting process:
public addLifecycleListener(lifeTimeOrLifecycle: string, listener: WeappLifecycleHook): OverrideWechatPage { // 针对指定周期定义Hooks this.lifecycleHooks[lifeTimeOrLifecycle].push(listener); const _Page = this.wechatOriginalPage; const _Component = this.wechatOriginalComponent; const self = this; const wrapMode = this.checkMode(lifeTimeOrLifecycle); const componentNeedWrap = ['component', 'pageLifetimes'].includes(wrapMode); const wrapper = function wrapFunc(options: IOverrideWechatPageInitOptions): string | void { const optionsKey = wrapMode === 'pageLifetimes' ? 'pageLifetimes' : ''; options = self.findHooksAndWrap(lifeTimeOrLifecycle, optionsKey, options); const res = componentNeedWrap ? _Component(options) : _Page(options); options.__router__ = (wrapper as any).__route__ = res; return res; }; (wrapper as any).__route__ = ''; if (componentNeedWrap) { overrideWxComponent(wrapper); } else { overrideWxPage(wrapper); } return this; }/** * 为对应的生命周期重写options * @param proxyLifecycleOrTime 需要拦截的生命周期 * @param optionsKey 需要重写的 optionsKey,此处用于 lifetime 模式 * @param options 需要被重写的 options * @returns {IOverrideWechatPageInitOptions} 被重写的options */private findHooksAndWrap = ( proxyLifecycleOrTime: string, optionsKey = '', options: IOverrideWechatPageInitOptions, ): IOverrideWechatPageInitOptions => { let processedOptions = { ...options }; const hooks = this.lifecycleHooks[proxyLifecycleOrTime]; processedOptions = OverrideWechatPage.wrapLifecycleOptions(proxyLifecycleOrTime, hooks, optionsKey, options); return processedOptions; };/** * 重写options * @param lifecycle 需要被重写的生命周期 * @param hooks 为生命周期添加的钩子函数 * @param optionsKey 需要被重写的optionsKey,仅用于 lifetime 模式 * @param options 需要被重写的配置项 * @returns {IOverrideWechatPageInitOptions} 被重写的options */private static wrapLifecycleOptions = ( lifecycle: string, hooks: WeappLifecycleHook[], optionsKey = '', options: IOverrideWechatPageInitOptions, ): IOverrideWechatPageInitOptions => { let currentOptions = { ...options }; const originalMethod = optionsKey ? (currentOptions[optionsKey] || {})[lifecycle] : currentOptions[lifecycle]; const runLifecycleHooks = (): void => { hooks.forEach((hook) => { if (currentOptions.__isPage__) { hook(currentOptions); } }); }; const warpMethod = runFunctionWithAop([runLifecycleHooks], originalMethod); currentOptions = optionsKey ? { ...currentOptions, [optionsKey]: { ...options[optionsKey], ...(currentOptions[optionsKey] || {}), [lifecycle]: warpMethod, }, } : { ...currentOptions, [lifecycle]: warpMethod, }; return currentOptions; };复制代码
After the above two steps, we can hijack the specified life cycle and inject our own listeners
, using the rewritten Component
or Page
These listeners
will be triggered automatically.
weapp-lifecycle-hook-plugin
In order to facilitate the direct implementation of this universal solution for the WeChat applet native environment and multi-terminal unified solutions such as Taro
, I Implemented a plug-in to solve this problem (selfish Amway)
Installation
npm install weapp-lifecycle-hook-plugin 或者 yarn add weapp-lifecycle-hook-plugin复制代码
Using
import OverrideWechatPage, { setupLifecycleListeners, ProxyLifecycle } from 'weapp-lifecycle-hook-plugin'; // 供 setupLifecycleListeners 使用的 hook 函数,接受一个参数,为当前组件/页面的options function simpleReportGoPage(options: any): void { console.log('goPage', options); } // setupListeners class App extends Component { constructor(props) { super(props); } componentWillMount() { // ... // 手动创建的实例和使用 setupLifecycleListeners 创建的实例不是同一个,所以需要销毁时需要单独对其进行销毁 // 直接调用实例方式 const instance = new OverrideWechatPage(this.config.pages); // 直接调用实例上的 addListener 方法在全局增加监听函数,可链式调用 instance.addLifecycleListener(ProxyLifecycle.SHOW, simpleReportGoPage); // setupListeners 的使用 setupLifecycleListeners(ProxyLifecycle.SHOW, [simpleReportGoPage], this.config.pages); // ... } // ... }复制代码
can solve the previous problem by simply setup
You need to manually write a lot of rewriting logic, why not do it
If you want to learn more about programming, please pay attention to the php training column!
The above is the detailed content of Understand the automatic tracking points of WeChat mini program Taro. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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



Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to
