Tracking click on anchors in an HTML page
There are many ways to track when a user clicks on a link in an HTML page. Most of them require loading a JS script and registering the click event for all <a>
elements. More recently, the ping
attribute was introduced to the <a>
element. It allows to specify a URL to ping when the link is clicked. So, there is no need for a JS script.
The ping
attribute is well-supported. Only Firefox disables this feature by default. Also, Ad Blockers may block the ping request (as they would block the JS script anyway). So, the global support is about 93.61%:
Using the ping
attribute provides some benefits:
<a ping>
works when JavaScript is disabled.<a ping>
requests are background requests. When the user leaves a page, the ping request will not be aborted.<a ping>
requests' response body is ignored; the browser is allowed to immediately end a connection when a response body is sent by the server. This may reduce the server and browser resources.<a ping>
responses are not cached as it's aPOST
request, so every ping will result in a request to the server.
Here's an example of a ping
attribute:
<a href="/demo" ping="/ping">Demo</a>
You can process the ping requests in your ASP.NET Core application. For example, you can log the ping request in the console:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseRouting();
app.MapPost("/ping", ([FromHeader(Name = "ping-from")]string from, [FromHeader(Name = "ping-to")] string to) =>
{
// TODO Do something with the ping request
Console.WriteLine(from + " -> " + to);
return Results.Ok();
});
app.MapRazorPages();
app.Run();
If you need to distinguish <a>
on the same page, you can use a query string parameter. For example, if you have two links on the same page, you can use <a ping="/ping?id=Link1">
and <a ping="/ping?id=Link2">
to distinguish them.
Do you have a question or a suggestion about this post? Contact me!