Friday, February 10, 2006

ImageVenue.com Image Focuser (Greasemonkey Userscript)

My ImageVenue Userscript

I have been annoyed by the junk they surround an image with when viewing an image at www.imagevenue.com. In the past I created a series of "site specific stylesheets", which look something like this:

@-moz-document domain(imagevenue.com) {
  .adHeadline {display: none;}
  #mbtb {display: none;}
  IFRAME {display: none ! important;}
  BODY > P > FONT {display: none ! important;}
  BODY > BR {display: none ! important;}
  P { margin: 0 ! important; }
}

This was over a long time, but it still had issues. First was that I was still loading the IFRAME, then I realised that I could simply use Adblock (Addons @ Mozilla homepage) to block the IFRAME.

Second, was trying to stop the page from scaling large images to a maximum width of 720 pixels. Hey, I have a 21" monitor, I have no problem displaying anything larger than 720 pixels. The scaling was happening in a JavaScript (JS) function that was attached to the images 'onLoad' event, meaning it would scale after the image has loaded. This means you get the annoying effect of viewing the image as it downloads in it's normal resolution, then it abruptly scales and stuffs you around!!

So I tried to make a Greasemonkey (GM) "Userscript" that would use the scale function again to return it to normal resolution. Since I am new to Greasemonkey, this took a little bit of getting used to.

  1. I tried calling the scaleImg() function in the Userscript. No dice, since the Firefox JS console reported that I don't have access to the function (I later read that you need to use specific GM API calls to work in the page's "sandbox" to get to its JS functions).
  2. Tried copy-n-pasting the scaleImg() code directly into my Userscript so sandboxing isn't an issue. Didn't work, as a variable saved for later was needed (the original width of the image), but I didn't have access to that.
  3. Using Firefox's Document Inspector, I discovered that I can get to the original width by accessing its "naturalWidth" DOM property. This still didn't work.
  4. I then found out I needed to run my code after the scaling function has been run from the onLoad event. Using the Tip from the GM Authoring page, I used:
    window.addEventListener("load", function(e) {
      what = document.getElementById('thepic');
      what.width=what.naturalWidth;
    }, false);
    This worked!! Though I then realised...
  5. That I could just "view" the plain image by changing the browser location to the image!! (redirection)
    what = document.getElementById('thepic');
    document.location = what.src;
    GM scripts run after a page has downloaded, but before any onLoad events have occurred. This means that my code is called before the image is downloaded (and maybe before it starts downloading).

So, it turned out to be dead simple, why didn't I think of that Before!!!!