pllee
pllee

Reputation: 3959

Capture all dynamic form submits

A couple of things that I am taking account for:

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.

  1. 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.

  2. 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:

  1. Use Object.defineProperty for the length property of document.forms.

  2. 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

Answers (1)

Oriol
Oriol

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

Related Questions