node.jsgoogle-analyticsnuxt.jsyandex-metrika

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


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.


Solution

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

    enter image description here