demarches-normaliennes/app/javascript/shared/safari-11-file-xhr-workaround.js

27 lines
1.1 KiB
JavaScript
Raw Normal View History

2018-08-31 12:56:56 +02:00
// iOS 11.3 Safari / macOS Safari 11.1 empty <input type="file"> XHR bug workaround.
// This should work with every modern browser which supports ES5 (including IE9).
// https://stackoverflow.com/questions/49614091/safari-11-1-ajax-xhr-form-submission-fails-when-inputtype-file-is-empty
// https://github.com/rails/rails/issues/32440
2020-04-30 15:42:29 +02:00
document.addEventListener('ajax:before', function (e) {
2018-08-31 12:56:56 +02:00
let inputs = e.target.querySelectorAll('input[type="file"]:not([disabled])');
2020-04-30 15:42:29 +02:00
inputs.forEach(function (input) {
2018-08-31 12:56:56 +02:00
if (input.files.length > 0) {
return;
}
input.setAttribute('data-safari-temp-disabled', 'true');
input.setAttribute('disabled', '');
});
});
// You should call this by yourself when you aborted an ajax request by stopping a event in ajax:before hook.
2020-04-30 15:42:29 +02:00
document.addEventListener('ajax:beforeSend', function (e) {
2018-08-31 12:56:56 +02:00
let inputs = e.target.querySelectorAll(
'input[type="file"][data-safari-temp-disabled]'
);
2020-04-30 15:42:29 +02:00
inputs.forEach(function (input) {
2018-08-31 12:56:56 +02:00
input.removeAttribute('data-safari-temp-disabled');
input.removeAttribute('disabled');
});
});