WEBcoast Logo

Safari: AJAX bug with `fetch`

When we do not have to support for old browser like the Internet Explorer, we can finally use new technologies. Though it is bad, if even a modern browser fails with those technologies.

In my case I tried to use fetch for the first time. fetch is more or less the successor of XMLHttpRequests, even though fetch lacks some things, so it could not be a complete replacement. Basically the syntax is much better and fetch uses Promises.

In my specific case, I wanted to send a form with fetch. This form contains among others a file upload field. The behaviour I experienced in Safari was, that the request never finished, no data was actually send. This only happened, if there were no files attached. Once I tried to upload one or more files, Safari just sends the request as it should.

After some hours of research I came to the conclusion, that the only way to work around this problem, is to disabled the file field, if no files are attached. Take the following code snippet as an example.

let formElementFiles = form.querySelector('[name="files[]"]');
// If no files are to be uploaded, disable the file field during initialization
// of FormData to make `fetch` work in Safari
if (formElementFiles && formElementFiles.files.length === 0) {
    formElementFiles.setAttribute('disabled', 'disabled');
}
let formData = new FormData(form);
// Re-enable the file field again
if (formElementFiles && formElementFiles.files.length === 0) {
    formElementFiles.removeAttribute('disabled');
}
fetch(url, {
    method: 'POST',
    // ....
});