Skip to content

Commit f770f2c

Browse files
committed
feat: implement Google Analytics page view tracking for Blazor applications.
1 parent 4d3f344 commit f770f2c

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

src/BlazorApps/Components/GoogleAnalytics.razor

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,47 @@
1414

1515
private MarkupString? _markup;
1616

17+
protected override void OnInitialized()
18+
{
19+
Nav.LocationChanged += OnLocationChanged;
20+
}
21+
22+
protected override async Task OnAfterRenderAsync(bool firstRender)
23+
{
24+
if (firstRender && !string.IsNullOrWhiteSpace(Id))
25+
{
26+
// Send initial page view
27+
await TrackPageView();
28+
}
29+
}
30+
31+
private async void OnLocationChanged(object? sender, LocationChangedEventArgs e)
32+
{
33+
await TrackPageView();
34+
}
35+
36+
private async Task TrackPageView()
37+
{
38+
var uri = Nav.ToBaseRelativePath(Nav.Uri);
39+
if (string.IsNullOrEmpty(uri))
40+
uri = "/";
41+
42+
await JS.InvokeVoidAsync(
43+
"gtag",
44+
"event",
45+
"page_view",
46+
new
47+
{
48+
page_path = "/" + uri
49+
}
50+
);
51+
}
52+
53+
public void Dispose()
54+
{
55+
Nav.LocationChanged -= OnLocationChanged;
56+
}
57+
1758
protected override void OnParametersSet()
1859
{
1960
if (string.IsNullOrWhiteSpace(Id))

0 commit comments

Comments
 (0)