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 · Tweet

You might also enjoy

Rails on Heroku

Jupyter + Rails

Securing Sensitive Data in Rails

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