Taro小程序接入灯塔分析SDK统计PV
思路:不修改代码,在一个全局都需要访问的地方埋点。最好能获取到用户的访问路径。
经过测试发现,Taro的navigateTo, redirectTo, switchTab, navigateBack都可以通过重现实现“代理”,来统计用户访问路径。
reportPV = (path = null) => {
if(!path){
this.getCurrentPage().then(res => {
this.reportPV(res)
})
const redirectTo = Taro.redirectTo
const navigateTo = Taro.navigateTo
const navigateBack = Taro.navigateBack
const switchTab = Taro.switchTab
Taro.redirectTo = data => {
this.reportPV(data.path||data.url)
redirectTo(data)
}
Taro.navigateTo = data => {
this.reportPV(data.path||data.url)
navigateTo(data)
}
Taro.navigateBack = data => {
this.getCurrentPage().then(res=>this.reportPV(res))
navigateBack(data)
}
Taro.switchTab = data => {
this.reportPV(data.url)
switchTab(data)
}
}else{
this.directReport({
event:'reportPV',
params:{path}
})
}
}
实现方式如上,但是仅仅是代理Taro的页面跳转函数是没有办法获取到用户进入的首页,同时小程序一开始加载的时候没有办法通过Taro.getCurrentPages()函数获得页面,因此需要定义一个异步函数getCurrentPage()来获得页面。
getCurrentPage = () => {
return new Promise((resolve,reject) => {
if(Taro.getEnv()===Taro.ENV_TYPE.WEAPP){
const time_id = setInterval(()=>{
const page = Taro.getCurrentPages()
if(page.length){
clearInterval(time_id)
resolve(page[0].route)
}
},250)
}else{
resolve(
window.location.pathname ?
this.customRoutes[window.location.pathname] ? this.customRoutes[window.location.pathname] : window.location.pathname
:'/pages/index/index'
)
}
})
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?