W3cubDocs

/DOM

WorkerNavigator.sendBeacon

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The NavigatorWorker.sendBeacon() method can be used to asynchronously transfer a small amount of data over HTTP from a worker to a web server. This is functionally equivalent to the Navigator.sendBeacon() method; see that article for additional details on what this method can be used for and why.

Syntax

self.navigator.sendBeacon(url, data);

Parameters

url
The url parameter indicates the resolved URL to which the data is to be transmitted.
data
The data parameter is a ArrayBufferView, Blob, DOMString, or FormData object containing the data to be transmitted.

Return value

The sendBeacon() method returns true if the user agent can successfully queue the data for transfer, Otherwise it returns false.

Example

The following example has two parts: first, the main thread creates a worker and sends it the message to forward to the server.

// Create a worker
var myWorker = new Worker('worker-beacon.js');

// Send the worker a message and set up a response callback

myWorker.postMessage('Send beacon!');

myWorker.onmessage = function(e) {
  var msg = e.data;
  console.log('Worker beacon reply: ' + msg);
};

In the following code snippet, we see the worker's Worker.onmessage event handler. The text passed as the message data when calling Worker.postMessage() is accepted by the event handler and sent to the server by calling sendBeacon().

// Worker's onmessage handler

onmessage = function(ev) {
  var msg = ev.data;
  self.navigator.sendBeacon('http://www.example.org/', msg);
}

Specifications

Specification Status Comment
Beacon
The definition of 'sendBeacon()' in that specification.
Editor's Draft Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support No support No support No support No support No support
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support No support No support No support No support No support No support No support

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/WorkerNavigator/sendBeacon