zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

How to integrate Baidu Analytics into a Nuxt project?

After deploying a website, one of our main concerns is undoubtedly the website traffic and its analysis. Baidu Analytics is a good choice for users in China, and its basic features are free.

You only need to include a JavaScript code snippet in the <head> section.

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

The above code is provided by Baidu Analytics and needs to be placed within the <head> tags.

However, in Nuxt projects, there is no traditional <head> section. Therefore, some modifications are required.

1. First, create a file named baidu.js in the /plugins directory at the root of the project.#

// /plugins/baidu.js

export default ({app: {router}, store}) => {
  /* Perform PV tracking on each route change */
  router.afterEach((to, from) => {
    /* Increase the PV count */
    try {
      window._hmt = window._hmt || []
      window._hmt.push(['_trackPageview', to.fullPath])
    } catch (e) {
    }
  })
}

2. Configure the nuxt.config.js file#

  1. In the plugins section:
plugins: [
  {
    src: '~/plugins/baidu'
  }
],
  1. In the head section:
head: {
  // ...
  link: [
    // ...
  ],
  script: [
    { src: 'https://hm.baidu.com/hm.js?xxxxxxxxxxxxxxxxxxx' }
  ]
},

Simply include the URL provided by Baidu Analytics in the script section, following the corresponding characters.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.