June 22, 2011
Lazy loading click handlers with onmousedown

Just today I was thinking about how annoying it is that Facebook redirects all outgoing links to an internal page. They do this to mitigate the spread of clickjacking worms and whatnot but I like to think I’m smart enough to not click a post titled “I can’t believe she isnt werring a bra LOL WORM!!” So I figured I’d write a quick greasmonkey script to switch the links back to their pristine form. Well, I didn’t exactly get around to writing the script but I discovered something nifty instead.

Take the following innocuous link to a humorous imgur image a friend posted on my wall:

<a href="http://i.imgur.com/7XSdO.jpg" target="_blank" rel="nofollow" 
    onmousedown="UntrustedLink.bootstrap($(this), &quot;SNIP&quot;, event, bagof(null));">
        http://i.imgur.com/7XSdO.jpg
</a>

The link target (href) is not rewritten on the server so the click must be getting intercepted via JavaScript. But you can’t preventDefault for a click via onmousedown, you have to catch the onclick event instead. Here’s what UntrustedLink looks like once beautified:

function UntrustedLink(a, d, b, c) {
    this.dom = a;
    this.url = a.href;
    this.hash = d;
    this.func_get_params = c ||
    function () {
        return {};
    };
    Event.listen(this.dom, 'click', this.onclick.bind(this));
    Event.listen(this.dom, 'mousedown', this.onmousedown.bind(this));
    Event.listen(this.dom, 'mouseup', this.onmouseup.bind(this));
    Event.listen(this.dom, 'mouseout', this.onmouseout.bind(this));
    this.onmousedown($E(b));
}

Facebook is adding onclick handlers to links right before the click happens. No wasting time with pesky onload initializations, links are self-initializing! Pretty neat.

12:51am  |   URL: http://tmblr.co/Zn_4by6KCv7l
  
Filed under: facebook javascript dom 
  1. paksoy posted this