This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.
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 thedata
is to be transmitted. data
- The
data
parameter is aArrayBufferView
,Blob
,DOMString
, orFormData
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 |