I want to use navigator.sendBeacon
in a client's website. But it is using the POST method and the request is not reaching the server as the request url's domain is different. I tried different ways of using sendBeacon()
, but all are using the POST method.
1.
var data = new FormData();<br>
navigator.sendBeacon(myurl, data);
navigator.sendBeacon(myurl, "");
navigator.sendBeacon(myurl);
Is there a way to make GET call using sendBeacon()
? Or is there any way to use sendBeacon()
in a cross-domain environment.
I want to use navigator.sendBeacon
in a client's website. But it is using the POST method and the request is not reaching the server as the request url's domain is different. I tried different ways of using sendBeacon()
, but all are using the POST method.
1.
var data = new FormData();<br>
navigator.sendBeacon(myurl, data);
navigator.sendBeacon(myurl, "");
navigator.sendBeacon(myurl);
Is there a way to make GET call using sendBeacon()
? Or is there any way to use sendBeacon()
in a cross-domain environment.
- maybe is a CORS problem? – Cristian Sepulveda Commented Aug 11, 2017 at 4:33
3 Answers
Reset to default 12From the W3C specification, on which browser implementations are based:
The sendBeacon() method does not provide ability to customize the request method. Applications that require non-default settings for such requests should use the FETCH API with keepalive flag set to true.
Per this documentation, here's an example of how the Fetch API can be used to replicate the behavior of sendBeacon
:
fetch(url, {
method: ...,
body: ...,
headers: ...,
credentials: 'include',
mode: 'no-cors',
keep-alive: true,
})
Although navigator.sendBeacon
uses POST you can still pass the data as a ?query=string
and this will reach the URL endpoint.
You can then simply parse the URL on the server and extract the data that way.
I use this for approach to debug production sites when I want to keep the DevTools closed but still see messages in my local terminal. Here is the output...
navigator.sendBeacon("http://127.0.0.1:8000/?"+string, string);
127.0.0.1 - - [28/Jan/2021 21:26:43] code 501, message Unsupported method ('POST')
127.0.0.1 - - [28/Jan/2021 21:26:43] "POST /?window-hidden HTTP/1.1" 501 -
127.0.0.1 - - [28/Jan/2021 21:27:42] code 501, message Unsupported method ('POST')
127.0.0.1 - - [28/Jan/2021 21:27:42] "POST /?window%20focus HTTP/1.1" 501 -
127.0.0.1 - - [28/Jan/2021 21:27:42] code 501, message Unsupported method ('POST')
127.0.0.1 - - [28/Jan/2021 21:27:42] "POST /?window%20blur HTTP/1.1" 501 -
127.0.0.1 - - [28/Jan/2021 21:27:42] code 501, message Unsupported method ('POST')
127.0.0.1 - - [28/Jan/2021 21:27:42] "POST /?window%20-%20hidden HTTP/1.1" 501 -
It seems that there is no full standardization of how browsers interpret sendBeacon(); some by default send on $_GET, and some on $_POST. they should use a 3rd argument to let the developer use GET or POST it would be more clear