Tracking click on anchors in an HTML page

 
 
  • Gérald Barré
 

There are many ways to track when a user clicks on a link in an HTML page. Most require loading a JavaScript script and registering click events on all <a> elements. More recently, the ping attribute was introduced for the <a> element. It lets you specify a URL to ping when a link is clicked, removing the need for JavaScript.

The ping attribute is well-supported. Only Firefox disables it by default, and ad blockers may block ping requests (just as they would block JavaScript-based tracking). Overall, global support sits at around 93.61%:

Can I use

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> response bodies are ignored; the browser can close the connection as soon as the server sends a response. This reduces resource usage on both the server and browser.
  • <a ping> responses are not cached as it's a POST request, so every ping will result in a request to the server.

Here's an example of a ping attribute:

HTML
<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:

C#
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();

To distinguish between multiple <a> elements on the same page, use a query string parameter. For example, use <a ping="/ping?id=Link1"> and <a ping="/ping?id=Link2"> to tell them apart.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?