单页应用(react、vue)等添加站长统计

2021-03-15
1分钟阅读时长

百度站长统计,给vue、react、angular等开发单页面应用,增加站长统计

核心思想是:监听hashchange事件以及在history模式下监听popstate事件

window.addEventListener('hashchange', function(e) {
  console.log(e)
})
window.addEventListener('popstate', function(e) {
  console.log(e)
})

单页应用(react、vue)等添加站长统计方法

1. 首先首页中引入

<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?7cca921d777c514ee1aec3d1c3cf26b5";
  var s = document.getElementsByTagName("script")[0]; 

2. vue如果使用了vue-router作为路由

router.afterEach((to, from, next) => {
  // 添加百度统计代码
  if (to.path) {
    _hmt.push(['_trackPageview', '/#' + to.fullPath]);
  }
  next();
});
···