Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Tuesday, May 25, 2021

Intercept HTML Forms Submit


 

In this post we will find a robust method of intercepting all HTML forms submit. 

One method to achieve the interception, is presented in this post, which uses addEventListener, and preventDefault. The problem is that in case another javascript code had also used addEventListener, it is not guaranteed which event listener would run first. Also, there are cases where preventDefault does not stop the event from triggering other javascript code.


The first thing to do is to run a scheduled code to scan HTML elements, and look for forms. This is required in case an HTML form is dynamically added to the page.



function captureForms() {
setInterval(scheduledCaptureForms, 1000)
}



Upon the scheduled activation, we find all forms, and update their submit to use an alternative custom code - our submit handled, instead of the original submit. We also make sure to do this replacement only once.



function scheduledCaptureForms() {
const forms = document.getElementsByTagName('form')
for (const form of forms) {
const key = 'formWasIntercepted'
if (!form[key]) {
form.originSubmit = form.submit
form.submit = function () {
submitHandlerAsync(form)
return false
}
form[key] = true
}
}
}



Finally, on our asynchronous submit handler, we can do what ever we want, and even activate the original submit once we've made our modifications.



async function submitHandlerAsync(form) {
let fetchUrl = form.action
if (!fetchUrl) {
fetchUrl = document.location.href
}

/*
do something before calling the original submit action
*/

form.originSubmit()
}







 

No comments:

Post a Comment