Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 34 additions & 14 deletions src/templates/_special/async-csrf-input.twig
Original file line number Diff line number Diff line change
@@ -1,19 +1,39 @@
<script>
(function() {
fetch('{{ url }}', {
headers: {
'Accept': 'application/json',
function fetchCsrfData() {
return fetch('{{ url }}', {
headers: {
'Accept': 'application/json',
},
}).then((response) => response.json());
}
function createHiddenInput({name, value}) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
return input;
}
function handleFocusIn(e) {
const asyncInput = e.currentTarget.querySelector('craft-csrf-input');
if (asyncInput) {
fetchCsrfData().then(({csrfTokenName, csrfTokenValue}) => {
const input = createHiddenInput({name: csrfTokenName, value: csrfTokenValue});
asyncInput.replaceWith(input);
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we also need to defer/debounce submit events that come in between focusin and injecting the input.

Over a slow connection, you could interact with the form and submit before the CSRF has been injected, resulting in a CSRF error.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe firing a csrfloaded event that bubbles up to the form would allow js to disable / enable the form submission.

}
}).then(response => response.json())
.then(data => {
document.querySelectorAll('craft-csrf-input')
.forEach(element => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = data.csrfTokenName;
input.value = data.csrfTokenValue;
element.replaceWith(input);
});
});
}
const asyncInputs = document.querySelectorAll('craft-csrf-input');
asyncInputs.forEach((el) => {
const form = el.closest('form');
if (!form) {
console.warning('craft-csrf-input should be within a form element.');
return;
}
form.addEventListener('focusin', handleFocusIn);
});
})();
</script>