Serexx Serexx - 1 month ago 22
Javascript Question

javascript intercepted form onsubmit has no return value

Given a Form element (in Chrome 53) that looks like this :

<form name="testForm" onsubmit="return onSubmit(event);">
<p>Test OnSubmit Hijack</p>
<input type="Submit" value="Submit" />
</form>


and this related onSubmit function:

<script type="text/javascript">
function onSubmit(e) {
console.log("onSubmit Event", e)
return false;
}
</script>


and having intercepted (aka hijacked) the form's "onsubmit" event like this:

<script>
(function () {
var f = document.forms[0];
var originalSubmit = f.onsubmit;
let result = "result init";
f.onsubmit = function (e) {
e.preventDefault();
console.log("Intercepted");
result = originalSubmit.apply(f, [e]);
console.log("user submit result", result);
return true;
};
})();
</script>


the variable
result
is always
undefined
. All the console results are otherwise what one would expect.

I'm pretty sure it has something to do with scoping / 'this' but after much head scratching I can't see it.

Any help greatly appreciated :-)

Answer

I tested your code in Chrome and it worked fine...

<!DOCTYPE html>
<html>
<body>
<form name="testForm" onsubmit="return onSubmit(event);">
    <p>Test OnSubmit Hijack</p>
    <input type="Submit" value="Submit" />
</form>
 <script type="text/javascript">
    function onSubmit(e) {
        console.log("onSubmit Event", e)
        return false;
    }
</script>
<script>
(function () {
    var f = document.forms[0];
    var originalSubmit = f.onsubmit;
    let result = "result init";
    f.onsubmit = function (e) {
        e.preventDefault();
        console.log("Intercepted");
        result = originalSubmit.apply(f, [e]);
        console.log("user submit result", result);
        return true;
    };
})();
</script>
</body>
</html>

Output from console:

Intercepted
test.html:10 onSubmit Event Event {isTrusted: true, type: "submit", target: form, currentTarget: form, eventPhase: 2…}
test.html:23 user submit result false