Blazor Newsfeed view duration tracking with IntersectionObserver
In the ever-evolving landscape of web development, tracking user engagement is crucial. For Blazor applications, the ability to monitor how long a user views a post can provide invaluable insights into user behavior and content effectiveness. In this tutorial, we will delve into implementing view duration tracking for a Blazor newsfeed application using the IntersectionObserver
API.
Prerequisites
Before we begin, ensure that you have a basic understanding of Blazor and JavaScript interoperability (JSInterop). This tutorial assumes you’re familiar with Razor components and client-side JavaScript.
Setting Up the Blazor Component
We’ll start by creating a FeedList.razor
component, which will contain our list of posts. Each post will be tracked for its visibility on the screen using the IntersectionObserver
.
FeedList Component
Here’s the setup for the FeedList.razor
component which lists the posts:
<div class="feed-container">
@foreach (var feed in FeedListData)
{
<FeedData feed="@feed" @key="feed.FeedID" />
}
</div>
@code {
[Parameter]
public List<tbFeed> FeedListData { get; set; } = new List<tbFeed>();
}
Feed Component
Next, let’s focus on the Feed
component which represents a single post:
<div @ref="feedElement" class="feed" id="@feed.FeedID">
@feed.TextBody
<hr />
</div>
@code {
[Parameter]
public tbFeed feed{ get; set; }
@inject IJSRuntime JSRuntime;
public ElementReference feedElement;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
var reference = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("observeFeed", feedElement, reference);
}
}
}
Implementing IntersectionObserver with JSInterop
To detect when a post becomes visible or hidden, we’ll use the IntersectionObserver
in our JavaScript code.
function observeFeed(element, dotNetObjRef) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(async (entry) => {
if (entry.isIntersecting) {
await dotNetObjRef.invokeMethodAsync('LogVisibilityChange', element.id, true, 0);
entry.target.startTime = Date.now();
} else if (entry.target.startTime) {
let duration = Date.now() - entry.target.startTime;
await dotNetObjRef.invokeMethodAsync('LogVisibilityChange', element.id, false, duration);
entry.target.startTime = null;
}
});
}, { threshold: [0.5] });
observer.observe(element);
}
The LogVisibilityChange Method
Finally, let’s add the LogVisibilityChange
method in the FeedData
component:
@code {
[JSInvokable]
public static Task LogVisibilityChange(string feedId, bool isVisible, long duration)
{
Console.WriteLine($"Feed{feedId} was {(isVisible ? "visible" : $"visible for {duration} milliseconds")}");
return Task.CompletedTask;
}
}
Conclusion
By integrating the IntersectionObserver
with Blazor using JSInterop, we can effectively track how long each post is visible to the user. This information can be used to analyze user engagement and optimize the content strategy accordingly. This approach showcases the power of combining modern JavaScript capabilities with Blazor's robust framework to enhance user experience and gather meaningful insights from user interactions.