Solve the problem that the onHide/onUnload method of the h5 page of uni-app is not triggered

background

  • Purpose: During the process of burying h5 pages, it is necessary to count the page browsing time and upload the burying log through life cycle monitoring.
  • Default plan: monitor the display/hide/destroy of the page through the onShow/onHide/onUnload life cycle of each page
  • Problem: The life cycle is only triggered normally on the homepage, onShow of other pages entered through jump is triggered normally, onHide and onUnload are not triggered.

Resolution process

  • Speculated reason: The page jumped through routing belongs to the second-level page, and the onHide and onUnload life cycles only exist in the first-level page.

Solution

  • secondary page:
    • onShow: Normally use this life cycle to monitor page display, including entering from the background to the foreground and routing jumps.
    • destroyed: Use component life cycle to replace onHide and onUnload, listen for route jump and leave
  • app.view:
    • onHide: The application life cycle monitors the entire application's foreground and enters the background, and distinguishes the buried log uploads of different pages through URLs.

Sample code

// 一级页面-首页
onShow() {
    
    
    this.$$DI.track('enter_page', {
    
    
        page_name: '首页'
    })
},
onHide() {
    
    
    this.$$DI.track('leave_page', {
    
    
        page_name: '首页'
    })
},
onUnLoad() {
    
    
    this.$$DI.track('leave_page', {
    
    
        page_name: '首页'
    })
},


// 二级页面
onShow() {
    
    
    this.$$DI.track('enter_page', {
    
    
        page_name: 'a页面'
    })
},
destroyed() {
    
    
    this.$$DI.track('leave_page', {
    
    
        page_name: 'a页面'
    })
}


// app.vue
onHide() {
    
    
    let page_name
    // 根据需要监听的页面路由进行判断添加
    if(window.location.href.includes('basic')) page_name = 'a页面'
    if(page_name) {
    
    
        this.$$DI.track('leave_page', {
    
    
            page_name
        })
    }
},

Guess you like

Origin blog.csdn.net/qq_44242707/article/details/129261410