I am trying to intercept form submits from webpages I dont control.
My current implementation is …
// During onLoad, loop through all forms and for each form object
var prevonsubmit = formobj.onsubmit;
if (prevonsubmit) {
formobj.onsubmit = function f() {
if(prevonsubmit()) {
interceptform();
return true;
}
return false;
};
} else {
formobj.onsubmit = function ff() {
interceptform();
return true;
};
}
The problem with this is, inside interceptform(), I am unable to identify which form actually made this submission. Is there a way I actually get the form object that is trying to submit? Keep in mind that some of the forms I see do not have a name or id specified and there is more than one form (in the same webpage) with same action.
Edit:
The purpose is capture the content in the input tags that belong to the form.
A made up example of what I see in a form:
<form action="https://duckduckgo.com/html/" method="GET">
<input type="text" name="q"/>
</form>
<form action="https://duckduckgo.com/html/" method="GET">
<input type="text" name="l"/>
</form>
<form action="https://duckduckgo.com/html/" method="GET">
<input type="text" name="l"/>
<input type="text" name="q"/>
</form>
Edit2:
Based on @ruakh answer, the solution I ended up using:
var prevonsubmit = formobj.onsubmit;
if (prevonsubmit)
formobj.onsubmit = createOnSubmitFunctionWithOld(prevonsubmit, formobj);
else
formobj.onsubmit = createOnSubmitFunction(formobj);
// Definition of the functions:
function createOnSubmitFunctionWithOld(prevonsubmit,formObj) {
return function () {
if (prevonsubmit()) {
interceptform(formObj);
return true;
}
return false;
};
}
function createOnSubmitFunction(formObj) {
return function () {
interceptform(formObj);
return true;
};
}
You can simply pass
formobjas an argument tointerceptform():But bear in mind that both with
formobjand withprevonsubmit, you have to be careful to avoid capturing a variable you don’t want to. For example, in JavaScript, this:creates ten functions that all return
10, because they all capture the sameivariable that’s been incremented up to10by the time the functions are ever called. In the above example, you could write something like:to copy each value of
iinto a new local variablereturn_valuewhose value never changes; or, a bit more tersely, this:You’ll almost certainly need to do something similar in your case. (But without seeing a bit more of the context of your code, it’s hard to say exactly what.)