Google Analytics Tag Helper Component

Introduction

In the last post, we talked about Tag Helper Components and how we can use them to modify existing HTML elements and inject scripts on the fly.

I needed Google Analytics scripts in my ASP.NET Core application, so I decided to make a NuGet package for that.

It is actually a Tag Helper Component.

Since MVC ships with Tag Helpers for Tag Helper Components that match the body and head tags, the setup is minimal. All you need to do is to install the package and add the GoogleAnalyticsTagHelperComponent to DI.

The script will be added at the end of the body element.

 

Installation

Install the NuGet package:

dotnet add package GoogleAnalyticsTagHelperComponent

or via Package Manager in Visual Studio:

Install-Package GoogleAnalyticsTagHelperComponent

Considering you have saved/copied your Google Analytics Tracking ID we can move on to the next and final step.

Add the Tag Helper Component to your app by injecting it into DI container.

If my Tracking ID was UA-99999-1 this is the code to use:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddSingleton<ITagHelperComponent>(new GoogleAnalyticsTagHelperComponent("UA-99999-1"));
}

And that’s it! On every page load, you should see the injected Google Analytics script with your Tracking Id in the HTML.

If you wanna inject the script to the head tag or some other custom tag you can do that as well:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddSingleton<ITagHelperComponent>(new GoogleAnalyticsTagHelperComponent("UA-99999-1"), "head");
}

 

 

Summary

It is pretty easy to hook up to built-in Tag Helpers (body, head) for Tag Helper Components and inject scripts or HTML via Tag Helper Components.

In one of the next posts, we might implement some Bootstrap components or/and pagination with help of Tag Helpers.

Enjoy!

Ibrahim Šuta

Software Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js.