views:

42

answers:

2

A browser element has an onpopupshowing attribute, which is a string consisting of several javascript statements.

I want to "override" that bit of javascript.

Were this a function, I'd just assign it to a variable, assign my "overriding" function to the element attribute, and (if need be) call the original function from my overriding one, pretty much like this:

var oldfunc;
function myoverrridingfunc () { my statement; oldfunc(); my other statement; }

oldfunc = element.getAttribute( "onpopupshowing" )
element.setAttribute( "onpopupshowing", myoverrridingfunc );

but element.getAttribute( "onpopupshowing" ) isn't a function, it's a string.

I could use the Function object to turn the string into a function, but the string includes references to this. How do I preserve the right this?

What's the best way of intercepting/overriding this bit of script? Note: this only needs to work in Firefox, not in any version of java/ECMAscript.

Thanks.

+1  A: 
var oldfuncStr = element.getAttribute("onpopupshowing");
element.removeAttribute("onpopupshowing");
var oldfunc = new Function(oldfuncStr);
element.addEventListener("popupshowing", function()
{
  myStatement;
  oldfunc.call(this);
  otherStatement;
}, false);

call is specifically for specifying this. I tested in Firefox, but with onclick event rather than onpopupshowing.

Matthew Flaschen
Thanks for your answer. A couple of questions: the original code needs the event parameter. Is that as simple as oldfunc.call(this, event)? Also, why the addEventListener, rather than just assigning an anonymous function to onpopshowing with setAttribute? Thanks for your patience.
tpdi
@tpdi, yes, that is how additional arguments are passed to `call`. Using the on-attributes is generally discouraged for several reasons, including the limit of one per element. But it will probably work fine here.
Matthew Flaschen
A: 

Perhaps you are overthinking this. Why not just wrap your JavaScript statements in quotes and assign it to the attribute? If the attribute expects JavaScript statements as a string, I wouldn't expect that assigning a function reference would even work anyway. (does it?)

gilly3