Is there any way (implemented or just in theory) that one could detect JavaScript events and actions assigned on a third party site?
If I am injecting JavaScript into a foreign site and want to avoid overwriting onsubmit, onclick, onfocus and other such events, is there any way to detect and extend such callbacks rather than overwrite them?
Ideas I’ve had:
- run the site in a headless browser or JavaScript engine before hand to capture all executed JavaScript
- parse the JavaScript on the fly and hope the third party JavaScript conforms to my parser’s expectations
If you just want to add new event handlers without overwriting the existing event handlers, you can use
addEventListener()orattachEvent()(for older versions of IE) instead of setting.onclick,.onsubmit, etc… to add a new event handler without affecting the previous event handlers.Here’s a simple cross browser function to add an event:
There is no cross browser way that I’m aware of from regular javascript to interrogate existing DOM objects to see which ones have regular javascript event handlers installed via
addEventListenerorattachEvent. If the event handlers are installed with jQuery, they can be interrogated via this technique.There is some future spec work that has been done to add a property that would list all the event handlers, but I am not sure it is implemented yet. You can read more about that here.
For event handlers installed with
onclick,onsubmit,onfocus, etc…, you can check all existing DOM elements to see which ones have handlers assigned for those events and you can then hook them if you want to.