I have a large project in which I need to intercept assignments to things like element.src, element.href, element.style, etc. I figured out to do this with defineSetter, but it is behaving very strangely (using Chrome 8.0.552.231)
An example:
var attribs = ["href", "src", "background", "action", "onblur", "style", "onchange", "onclick", "ondblclick", "onerror", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onmousedown", "onmousemove", "onmouseover", "onmouseup", "onresize", "onselect", "onunload"];
for(a = 0; a < attribs.length; a++) {
var attrib_name = attribs[a];
var func = new Function("attrib_value", "this.setAttribute(\"" + attrib_name + "\", attrib_value.toUpperCase());");
HTMLElement.prototype.__defineSetter__(attrib_name, func);
}
What this code should do is whenever common element attribute in attribs is assigned, it uses setAttribute() to set a uppercased version of that attribute.
For some very strange reason, the setter works for only ~1/3 of the assignments.
For example with
element.src = "test"
the new src is “TEST”, like it should be
however with
element.href = "test"
the new href is “test”, not uppercase
then even when I try element.__lookupSetter__("href"), it returns the proper, uppercasing setter
the strangest thing is different variables are intercepted properly between Chrome and Firefox
help!!
This is not a good idea. Host objects (such as DOM elements) are not subject to the usual rules that apply to native JavaScript objects and can essentially do what they like, and all browsers to a greater or lesser extent take advantage of this fact. Browsers are not obliged to provide a prototype for host objects, and neither are they obliged to allow you to override getters and setters for host object properties, or respect any attempts to override default behaviour.
I’d strongly recommend abandoning this approach and take a different approach instead, such as writing wrapper objects for DOM elements.
UPDATE: Example of wrapper approach
You can create wrapper objects for DOM elements and do all DOM manipulation through these wrappers. This is something many libraries (such as YUI) do. For example: