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. .
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
.
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)?
The most important thing is to think from scratch, grasp the real problem, and get close to the essence of the 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
.
Before solving this problem, we have to separate the problems we need to solve:
options
options should be rewritten
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;
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[]>); }复制代码
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.
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)
npm install weapp-lifecycle-hook-plugin 或者 yarn add weapp-lifecycle-hook-plugin复制代码
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!