Vuepress configuration Baidu statistics

Vuepress configuration Baidu statistics

1. Add Baidu statistics

Obtain Baidu Statistics Code
Log in to Baidu Statistics Backend
Create Site
Copy Statistics Code

var _hmt = _hmt || [];
(function() {
    
    
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?44212d6ce872df50b804d94b24889284";
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(hm, s);
})();

#Configure Baidu statistics code
vi ./config.js

head: [
    // 添加百度统计
    [
      "script",
      {
    
    },
      `
      var _hmt = _hmt || [];
      (function() {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?44212d6ce872df50b804d94b24889284";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
        `
    ]
  ]

::: tip #Manually
report pv statistics when switching pages.
There is currently a problem that Baidu statistics will be triggered only when you visit the homepage or refresh the page.
:::

Because vuepress is a single-page application based on vue, the page will not be reloaded during the page switching process, so Baidu statistics will not be triggered.

Solution: Listen for routing switching events, and manually report Baidu statistics when switching pages. The specific implementation is as follows:
vi .vuepress/enhanceApp.js

export default ({
    
     router }) => {
    
    
  /**
   * 路由切换事件处理
   */
  router.beforeEach((to, from, next) => {
    
    
    console.log("切换路由", to.fullPath, from.fullPath);

    //触发百度的pv统计
    if (typeof _hmt != "undefined") {
    
    
      if (to.path) {
    
    
        _hmt.push(["_trackPageview", to.fullPath]);
        console.log("上报百度统计", to.fullPath);
      }
    }

    // continue
    next();
  });
};

::: tip
Whenever the route is switched, the statistics report will be triggered. Therefore, statistics will be reported when the following actions occur:
:::

First visit
Refresh the page
Switch to other chapters of the current article
Switch the anchor point, the URL will change, so the route change event will be triggered.
Therefore, when the user has finished browsing a blog, multiple reports may be triggered.

Baidu Statistics official js-api document (https://tongji.baidu.com/open/api/more?p=guide_overv)

Guess you like

Origin blog.csdn.net/qq_39367226/article/details/107449882
Recommended