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'
                    )
            }
        })
    }
posted @ 2022-09-28 20:26  Scok  阅读(63)  评论(0编辑  收藏  举报