Forum Moderators: open

Message Too Old, No Replies

Intercepting existing events on a page

Can I intercept existing event handlers without breaking them?

         

frobozz

1:12 pm on Oct 18, 2013 (gmt 0)

10+ Year Member



I have a service that clients use by pasting a bit of JavaScript into their page. I've been tasked with executing a specific function if, and only if, the page in question has one or more forms on it *and* the user submits one of those forms.

There are of course many variations in how forms are implemented, but for now I'm only concerned with traditional forms -- ones that have a <form> tag and are submitted by a type="submit" control or an object that uses "submit()."

My idea is to traverse the DOM and identify any/all form submit controls, and then intercept the submission to do my own thing.

My question is this: if I intercept form submission, and I return true after executing my function, will the original code run as intended? For instance, if the page was using JavaScript form validation, will that validation still run after I've done my own thing?

Or is there a better way to accomplish my goal?

If this is confusing or unclear, I'll try to reword it.

frobozz

2:10 pm on Oct 18, 2013 (gmt 0)

10+ Year Member



I figured it out:

 function my_function() {
alert("Hello");
}

var my_var = document.getElementsByTagName("form");
for (var counter = 0; counter < my_var.length; counter++) {
my_var[counter].addEventListener('submit',my_function,false);
}


This is rough code (should check for addEventListner vs. attachEvent) but it's what I was after. I intercept all form submissions, run my function, then submission continues.