(function(window) {
injectCsrfToken(document.querySelectorAll('form'));
function injectCsrfToken(forms) {
for (var i = 0; i < forms.length; i ++) {
if (isValidForm(forms[i])) {
var csrfInput = document.createElement('input');
csrfInput.setAttribute('type', 'hidden');
csrfInput.setAttribute('name', 'authenticity_token');
csrfInput.setAttribute('value', 'f62e37af83d9452a164f06001495aaf5f9477bce2c5667d4ccc914524b4f5c12');
forms[i].insertBefore(csrfInput, forms[i].firstChild);
}
}
}
function isValidForm(form) {
var method = form.getAttribute('method') || '';
var action = form.getAttribute('action') || '';
if (form.querySelector('input[name="authenticity_token"]')) {
// The form is already protected
return false;
}
if (method.toLowerCase() !== 'post') {
//The form method is not post
return false;
}
if (RegExp('^(?:[a-z]+:)?//', 'i').test(action) && action.indexOf(window.location.hostname) === -1) {
// if url is absolute and pointing to a different host name
return false;
}
return true;
}
const callback = function(mutationsList) {
for (let mutation of mutationsList) {
for (let node of mutation.addedNodes) {
if((node.hasChildNodes())) {
injectCsrfToken(node.querySelectorAll('form'));
}
}
}
};
const observer = new MutationObserver(callback);
observer.observe(document.getElementsByTagName("BODY")[0], {childList: true, subtree: true});
})(window);