sendBeacon API not working temporarily due to security issue, any workaround?

webblover picture webblover · Jul 24, 2017 · Viewed 10.5k times · Source

I have the following code to send asynchronous HTTP request using sendBeacon method,

var data = {
 name: 'test',
 uniqueId: Math.random()
};
var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
navigator.sendBeacon('http://example.in/data/post', blob);

This code has worked fine for a long time. Currently, due to security issues in chrome https://bugs.chromium.org/p/chromium/issues/detail?id=490015, we see the error "Failed to execute 'sendBeacon' on 'Navigator': sendBeacon() with a Blob whose type is not CORS-safelists MIME-type is disallowed experimentally. See http://crbug.com/490015 for details."

Is there any workaround to send JSON data by modifying request headers using the same sendBeacon API till the issue is fixed? It'll be useful for sites depending on this API to continue to use till a fix is made. Suggestions on using XHR to post data are not useful.

Answer

Vidhi Khanna picture Vidhi Khanna · Aug 10, 2017

The only allowed values for the Content-Type header in sendBeacon now are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

I had a similar issue in our project and I ended up sending the data as 'text/plain; charset=UTF-8' and reading the stream on server side for the json content.

Client:

const blob = new Blob([JSON.stringify(myData)], { type: 'text/plain; charset=UTF-8' });
navigator.sendBeacon(appData.ReleaseSessionUrl, blob);

Server:

using (var reader = new StreamReader(this.Request.InputStream))
{
   var jsonData = reader.ReadToEnd();
   var sessionData = JsonConvert.DeserializeObject<MyDataType>(jsonData);
}

Not sure if this helps you.

https://github.com/GoogleCloudPlatform/stackdriver-errors-js/issues/10