demarches-normaliennes/app/javascript/shared/rails-ujs-fix.js

42 lines
1.3 KiB
JavaScript
Raw Normal View History

import Rails from '@rails/ujs';
import jQuery from 'jquery';
// `smart_listing` gem is overriding `$.rails.href` method. When using newer
// jQuery-less version of rails-ujs it breaks.
// https://github.com/Sology/smart_listing/blob/master/app/assets/javascripts/smart_listing.coffee.erb#L9
addEventListener('load', () => {
2018-11-20 11:57:03 +01:00
const { href, handleRemote } = Rails;
2020-04-30 15:42:29 +02:00
Rails.href = function (element) {
return element.href || href(element);
};
2020-04-30 15:42:29 +02:00
Rails.handleRemote = function (e) {
2018-11-20 11:57:03 +01:00
if (this instanceof HTMLElement) {
handleRemote.call(this, e);
} else {
let element = e.find('[data-remote]')[0];
let event = new CustomEvent('click');
Object.defineProperty(event, 'target', { value: element });
return handleRemote.call(element, event);
}
};
});
// rails-ujs installs CSRFProtection for its own ajax implementation. We might need
// CSRFProtection for jQuery initiated requests. This code is from jquery-ujs.
jQuery.ajaxPrefilter((options, originalOptions, xhr) => {
if (!options.crossDomain) {
CSRFProtection(xhr);
}
});
function csrfToken() {
return jQuery('meta[name=csrf-token]').attr('content');
}
function CSRFProtection(xhr) {
let token = csrfToken();
if (token) {
xhr.setRequestHeader('X-CSRF-Token', token);
}
}