Reputation: 3959
A couple of things that I am taking account for:
Forms can be inserted into the dom at any point in time. A dom ready listener and iteration over document.forms
is not an option.
Adding this submit capturing logic is a nice to have, it should work cross browser but adding jQuery
to make it work would be overkill.
We are using a very heavy dom manipulation framework and the solution shouldn't hurt the overall applications performance.
I don't want to add dom insertion listeners because they are slow and the framework that we use inserts items into the dom quite often.
Overriding HTMLFormElement.prototype.submit
works when .submit()
is programatically called but not when the user triggers a form submit through purely browser interaction. I found that listening to the submit event works for both cases but in order to listen to the event you need a reference to each form instance. All form instances can be obtained through document.forms
but document.forms
is a HTMLCollection and there isn't an api to monitor changes MutationObservers only work with Nodes
not HTMLCollections
. The two approaches that I believe will work seem quite messy.
setInterval
can be used to monitor document.forms
and if a new form has been added to the HTMLCollection
add the listener to the form.
Monitor document mutation events and add a listener when a form
is inserted into the dom.
Other ugly approaches that I tried that did not work:
Use Object.defineProperty
for the length property of document.forms
.
Override constructor of HTMLFormElement
to run the normal construction logic and then add an event listener for submit
.
Any tips on advice on what to do? I am leaning towards using setInterval
but that approach is not guaranteed to work under all scenarios.
Upvotes: 1
Views: 164
Reputation: 288100
In order to capture forms submitted by user, you could use event delegation to body.
Then:
// Capture user submitted forms:
document.body.addEventListener('submit', function (e) {
/* `e.target` is the form being submitted
Use `e.preventDefault()` to prevent submitting it */
}, false);
// Capture programmatically submitted forms:
var _submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = function () {
/* `this` is the form being submitted
Use `_submit.call(this)` to submit it */
};
Upvotes: 3