I found many answers here and elsewhere on preventing CSRF.
I managed to convert them from jQuery to ES6. Sadly it only works well for input
, but not for textarea
elements.
/* Prevent click-jacking with invisible iframes */
if (top.location !== window.location)
top.location = window.location;
/* Prevent HTML tags in inputs and textareas */
const sanitizationRegex = /<(|\/|[^>\/bi]|\/[^>bi]|[^\/>][^>]+|\/[^>][^>]+)>/g
const inputs = [...document.querySelectorAll('input')]
const textareas = [...document.querySelectorAll('textarea')]
const sanitizeInput = function(element) {
element.value = element.value.replaceAll(sanitizationRegex, '')
}
const sanitizeTextarea = function(element) {
element.innerText = element.innerText.replaceAll(sanitizationRegex, '')
element.innerHTML = element.innerHTML.replaceAll(sanitizationRegex, '')
};
inputs.forEach(element => {
element.addEventListener('keyup', () => sanitizeInput(element))
element.addEventListener('change', () => sanitizeInput(element))
});
textareas.forEach(element => {
element.addEventListener('keyup', () => sanitizeTextarea(element))
element.addEventListener('change', () => sanitizeTextarea(element))
})
As you can see I tried using innerText
as well as innerHTML
for textarea
but neither worked. I also tried the same thing with innerContent
but that just resulted in error logs.
Note: Here's a CodePen, with the first three lines removed.