Extending the DOM

From GreaseSpot
Jump to: navigation, search

Sometimes you might want to emulate proprietary functionality of another browser, for instance when a site uses such features:

var getter = function() { return this.textContent; };
var setter = function(t) { return this.textContent = t; };
unsafeWindow.HTMLElement.prototype.__defineGetter__("innerText", getter);
unsafeWindow.HTMLElement.prototype.__defineSetter__("innerText", setter);

Similarly here's an implementation of the Internet Explorer specific .outerHTML property.

function outerHTML(el){
  // create range of element
  var rng=document.createRange();
  rng.selectNode(el);
  // create temp span around element
  var tempSpan=document.createElement("span");
  rng.surroundContents(tempSpan);
  // what we came for
  var oHTML=tempSpan.innerHTML;
  // remove temp span
  rng.selectNodeContents(tempSpan);
  var frag = rng.cloneContents();
  tempSpan.parentNode.replaceChild(frag, tempSpan);
  // remove range
  rng.detach();
  // output
  return oHTML;
}

It's also possible to override browser constants, for instance change the value of navigator.userAgent.

var real = window.navigator.userAgent;
var lie = function() { return real + " Macintosh"; };
unsafeWindow.navigator.__defineGetter__("userAgent", lie);

In all cases, however, it's best to avoid using unsafeWindow. The Location hack is always preferred.

Personal tools