navigator.sendBeacon and Rails

navigator.sendBeacon is a neat new API. It allows you to send an asynchronous POST request without delaying the page unload.

To prevent Can't verify CSRF token authenticity with Rails, use the method below:

var data = new FormData();
data.append("hello", "beacon");

// add CSRF
var param = document.querySelector("meta[name=csrf-param]").getAttribute("content");
var token = document.querySelector("meta[name=csrf-token]").getAttribute("content");
data.append(param, token);

navigator.sendBeacon("/beacon", data);

For a real-world use case, check out Ahoy.js.


Published September 1, 2016

You might also enjoy

Argon2 with Devise

Package Your JavaScript Libraries With Rollup

Bootstrapping Postgres Users

All code examples are public domain.
Use them however you’d like (licensed under CC0).