[Greasemonkey] Re: Cloning a DOM Object including its events

Jeremy Dunck jdunck at gmail.com
Mon Oct 3 11:09:59 EDT 2005


On 10/3/05, Mor Roses <moroses at gmail.com> wrote:
> Is there no way to do it?

There's no way to iterate existing event listeners.  If the source
page is using onevent attributes, you can just copy those.

events from:
http://www.mozilla.org/docs/dom/domref/dom_event_ref33.html

so this is something like what you want.

var events = [
'mousedown', 'mouseup', 'click', 'dblclick', 'mouseover', 'mouseout',
'mousemove', 'contextmenu', 'keydown', 'keyup',
'keypress', 'focus', 'blur', 'load', 'unload', 'abort', 'error',
'submit', 'reset', 'change', 'select', 'input',
'paint', 'text', 'popupShowing', 'popupShown', 'popupHiding',
'popupHidden', 'close', 'command', 'broadcast',
'commandupdate', 'dragenter', 'dragover', 'dragexit', 'draggesture',
'resize', 'scroll', 'underflow',
'overflowchanged', 'subtreemodified', 'nodeinserted', 'noderemoved',
'noderemovedfromdocument',
'nodeinsertedintodocument', 'attrmodified', 'characterdatamodified'
]

var clone = template.cloneNode(true);

for (var i=0, e=events[0]; e=events[i++];) {
  clone['on'+e] = template['on'+e] ? template['on'+e] : null;
}

Note, though that if you cloneNode recursively, you'll want to recurse
down all the children to loop over all their onevent attributes, too.
....

If that's not good enough, and the content event listeners aren't
added page load (or later), you can override the content
addEventListener and removeEventListener to capture the registrations.
 You'll want to keep a dictionary keyed by node with array values. 
This is not trivial and will cause horrible performance if there are
lots of registered handlers, so only do that if you know what you're
doing.  :)


More information about the Greasemonkey mailing list