Menu

How I count a fair ad view: IntersectionObserver, sendBeacon and server-side dedupe
📰

How I count a fair ad view: IntersectionObserver, sendBeacon and server-side dedupe

DEV Community: frontend·Nir Wolff·7 days ago
#YGXXk6Hz
#devtofrontend#devto#dev#view#timer
Reading 0:00
15s threshold

I run a small cross-promo network for apps built with AI. Each member puts a little card on their site that shows other members' apps, and every view earns them a token. That means the view counter is the economy. If it counts too much, people farm tokens. If it counts too little, hosts feel cheated.

Here's how the embed decides what a "view" is, in about 40 lines of plain JavaScript.

1. Only count what people can actually see

A card at the bottom of a long page that nobody scrolls to shouldn't earn anything. IntersectionObserver tells us when the card is on screen, and a timer makes sure it stays there:

var sent = false , timer = null ; function send () { if ( sent ) return ; sent = true ; var u = origin + " /api/view?imp= " + encodeURIComponent ( ad . imp ); if ( navigator . sendBeacon ) navigator . sendBeacon ( u ); else fetch ( u , { method : " POST " , keepalive : true }); }

var io = new IntersectionObserver ( function ( entries ) { entries . forEach ( function ( e ) { if ( e .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.