Push Button, Receive Beacon

A presentation at BristolJS in July 2018 in Bristol, UK by Drew McLellan

Slide 1

Slide 1

Push button, Receive Beacon

Slide 2

Slide 2

Beacon API

JavaScript-based Web API in modern browsers for sending small amounts of data to the web server without waiting for a response.

We don't even get a response if we want one.

www.w3.org/TR/beacon

Slide 3

Slide 3

Why would we want that?

A number of use cases fall into the send and forget model.

Slide 4

Slide 4

Analytics

Log page views, time on page, interaction patterns, what was shown?

Diagnostic logging

Trap errors in production and report back

Multivariate tests

Track which variants were used and how they performed and so on...

Slide 5

Slide 5

We can do this already

I know what you're thinking. We can do this with the Fetch API or XHR. But can we? Yes. however...

Slide 6

Slide 6

Non-blocking

Unlike everything else, Beacon is non-blocking. It doesn't return a result, so the browser can background the request and let code execution continue.

Slide 7

Slide 7

Turns out this is super important

Many logging behaviours are fired when the user leaves the page on the unload or beforeunload events.

Slow running code (like duh, HTTP requests) in these events kills performance.

Beacon queues the request and lets the browser continue, executing it in the background when it can.

Slide 8

Slide 8

Basic use

let result = navigator.sendBeacon(url, data);

Slide 9

Slide 9

Posting data

The data parameter can be in one of several formats, all if which are taken directly from the Fetch API.

  • Blob
  • BufferSource
  • FormData
  • URLSearchParams

Slide 10

Slide 10

Posting data

let url = '/api/my-endpoint';

let data = new FormData();
data.append('hello', 'world');
 
let result = navigator.sendBeacon(url, data);
 
if (result) console.log('Successfully queued!');

Slide 11

Slide 11

Browser support

https://caniuse.com/#search=beacon

Slide 12

Slide 12

Browser support

It's easy to test for:

if (navigator.sendBeacon) {
	// Beacon code
} else {
	// No Beacon. Maybe fall back to XHR?
}

Slide 13

Slide 13

Logging page view time

let startTime = performance.now();

let logVisit = function() {

	if (!navigator.sendBeacon) return false;

	let url = '/api/log-visit';
	
	let data = new FormData();
	data.append('start', startTime);
	data.append('end', performance.now());
	data.append('url', document.URL);

	navigator.sendBeacon(url, data);
};

window.addEventListener('beforeunload', logVisit);

Slide 14

Slide 14

Considerations when logging

GDPR Maybe don't log stuff you don't need to log. Don't identify any sessions without considering privacy and your permitted use.

Do Not Track If you can, honour the user's DNT header.

DNT: 0
DNT: 1

Slide 15

Slide 15

Thanks!

I'm @drewm

Slides on Notist: noti.st/drewm