T
T
ThunderCat2018-02-02 15:52:45
JavaScript
ThunderCat, 2018-02-02 15:52:45

Does not catch the submit event from the connected js, where to dig?

Task: Catch the form firing on the page.
There is the following code:

$(document).ready(function () {
    $(document).on('submit','form',function(e){
          alert('wtf?');
     })
})

in externally included js there is a code of the following content, which is triggered by clicking on a certain element:
h.redirect = function (a, b) {
        var c = k.createElement("form");
        c.action = b;
        c.method = "post";
        c.target = "_top";
        c.style.display = "none";
        var d = k.createElement("input");
        d.type = "hidden";
        d.name = "token";
        d.value = a;
        c.appendChild(d);
        k.body.appendChild(c);
        c.submit()
    }

Attention to the question: When c.submit() does not catch anything, the coconut does not grow, the alert does not come out, but the form works and the submit occurs. How to catch an event, or at least explain why such a crap? Doesn't c.submit() create an event?
UPD: Thanks everyone, I'm a dumb moose, I didn't look at the code properly, nor the fact where the callback is described without submitting.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kovalsky, 2018-02-02
@ThunderCat

In general, it's not very cool that a third-party script allows itself such liberties as a direct call to submit , or maybe it's some specific one. This approach leaves no choice but to decorate:

(() => {
    var old_submit = HTMLFormElement.prototype.submit;

    HTMLFormElement.prototype.submit = function() {
        var form = this,
            args = Array.prototype.slice.call(arguments),
            submit_event = new Event('submit', {
                bubbles: true,
                cancelable: true
            });

        submit_event.original_submit = function() {
            old_submit.apply(form, args);
        };

        form.dispatchEvent(submit_event);
    }
})();

$(() => {
    var my_form = $( 'form' )[0];

    $( document )
        .on('submit', 'form', function(e) {
            alert('wtf?');
            e.originalEvent.original_submit();
        })
        .on('click', 'button', function() {
            my_form.submit();
        });
})

The bottom line is to throw out (bubbling) the event object when submit is called, in which there is a link to the original submit, which is the only way to send the form. This is horror, a nightmare and hell, and I would never do that, but I couldn’t think of anything better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question