Creates JavaScript tracking snippet for Google Analytics client tracking. For more information visit Google documentation.
You can do this by writing:
<dc:GoogleAnalyticsJavascript TrackingId="UA-XXXXX-Y" PageViewEnabled="true" AsyncVersionEnabled="true"/>
That will be rendered in HTML and look like this:
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script src="https://www.google-analytics.com/analytics.js" async=""></script>
You can also inject GoogleAnalyticsOptions
via dependency injection.
- First you need to register option from configuration:
services.Configure<GoogleAnalyticsOptions>(
Configuration.GetSection("GoogleAnalyticsOptions"));
- Then add Google Analytics options to your configuration (e.g.: appsettings.json):
{
"GoogleAnalyticsOptions": {
"TrackingId": "UA-XXXXX-Z",
"PageViewEnabled": false,
"AsyncVersionEnabled": false
}
}
- As the last step, you need add
dc:GoogleAnalyticsJavascript
in your page:
<dc:GoogleAnalyticsJavascript />
And this is the result that has been rendered:
<script type="text/javascript">
(function(i, s, o, g, r, a, m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q = i[r].q ||[]).push(arguments)},i[r].l=1*new Date(); a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a, m)})(window, document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-Z', 'auto');
</script>