Blazor extensions for Analytics: Google Analytics, GTAG, etc...
AspNetCore Version: 3.1.8
https://nuget.org/packages/Blazor-Analytics
First, import the namespaces in _Imports.razor
@using Blazor.Analytics
@using Blazor.Analytics.Components
Then, add the NavigationTracker
component below your Router in App.razor
.
The tracker listens to every navigation change while it's rendered on a page.
<Router ... />
+ <NavigationTracker />
Edit _Host.cshtml
and apply the following change:
<script src="https://github.com/isc30/blazor-analytics/raw/master/_framework/blazor.server.js"></script>
+ <script src="https://github.com/isc30/blazor-analytics/raw/master/_content/Blazor-Analytics/blazor-analytics.js"></script>
Edit index.html
and apply the following change:
<script src="https://github.com/isc30/blazor-analytics/raw/master/_framework/blazor.webassembly.js"></script>
+ <script src="https://github.com/isc30/blazor-analytics/raw/master/_content/Blazor-Analytics/blazor-analytics.js"></script>
Inside your main Startup
/Program
, call AddGoogleAnalytics
. This will configure your GTAG_ID automatically.
+ services.AddGoogleAnalytics("YOUR_GTAG_ID");
IAnalytics
wherever you want to trigger the event.IAnalytics.TrackEvent
passing the EventName
and EventData
(an object containing the event data).
IAnalytics.TrackEvent
passing the EventName
, Value
and Category
(optional).@inject Blazor.Analytics.IAnalytics Analytics
Analytics.TrackEvent("generate_lead", new {currency = "USD", value = 99.99});
1.- Inject ITrackingState on blazor component
@using Blazor.Analytics.Abstractions
@using Blazor.Analytics
@inject ITrackingNavigationState TrackingNavigationState
@inject IAnalytics GlobalTracking
2.- Disable tracking on initialized
2.1 For current page
protected override void OnInitialized()
{
TrackingNavigationState.DisableTracking();
}
2.2 For whole application
protected override void OnInitialized()
{
GlobalTracking.Disable();
}