Add to Nuxt.js application analytics script, which execution depends on current url

848 Views Asked by At

I have Nuxt.js application which is using 'universal' mode.

My task is to insert Yandex-metrika(similar to Google analytics) into my Nuxt.js application.

I have three problems:

  1. script should be used on every page
  2. script should be used only in production environment
  3. script should be used only on specific domain, for example: domain.com

I tried to use app.html to include my script. First two problems are solved with below solution, but last one remains: how to know current url? I have no access to window from Nuxt.js template syntax, window.location.host would have solve my problem easily.

app.html

{% if (process.env.NODE_ENV === 'production') { %}
<!-- Yandex.Metrika counter -->
<script type="text/javascript" >
  // script execution
</script>

<noscript>
  <div>
    <img src="https://mc.yandex.ru/watch/00000000" style="position:absolute; left:-9999px;" alt="" />
  </div>
</noscript>
<!-- /Yandex.Metrika counter -->
{% } %}

I can add condition statement to my <script>, like if (window.location.host === 'domain.com') but what to do with <noscript> then? How to conditionally hide it?

I also considered to putting alalytics script into plugin, but this solution has side problems - analytics does not work well.

2

There are 2 best solutions below

0
On BEST ANSWER

Check the option Receive data only from specified adresses to prevent sending extraneous data to your reports from unneeded domains.

enter image description here

0
On

3- You should not worry about the noscript tag, it's only a fallback when javascript is disabled on your browser.

The noscript HTML element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser.

1- As you said for this problem you can use different approaches like plugins, app.html (with window.location.host and check for correct domain), etc.

2- for the second problem you can use the .env file and set different values for different environments(production, staging, etc), and use procss.env.GA_ID, in the nuxt.config.js file, inside head property you can load scripts conditionally.

.env file

GA_ID=UA-17XXXX23-X
// example with analytics
// nuxt.config.js
// inside export default
head: {
   script: [
      {
         src: 'https://www.googletagmanager.com/gtag/js?id=' + process.env.GA_ID
      },
      {
         src: '/gtm.js'
      }
   ],
}