Monday, August 27, 2012

Running Greasemonkey functions from page events

As you know, I wrote a simple Greasemonkey script to hide multiple results from one domain in Google searches.  This script worked very well, and was easy to set up, but I had originally wanted to have the ability to click to show the hidden results.  Doing this in javascript is pretty simple, but Greasemonkey runs all scripts in a sandbox which cannot be accessed from the page.  This is somehow related to security, which I won't pretend to understand.

I was pretty content with how the script was, but someone on the script's page requested the click to show feature, and I figured I would give it a try.

Greasemonkey has something called the unsafewindow for stuff that must break out of the sandbox, and I got click to show working pretty fast using it.  The problem is that everyone has a dogmatic animosity towards using it.  So, I decided to try to figure out one of the alternatives

The most common suggestion was to use the location hack, which just puts the function in a bookmarklet and links to it.  If you don't know, you can run javascript on a page by just pasting it into your url bar.  Prior to Greasemonkey, I used a lot of these via bookmarks called bookmarklets.  Anyway, this is all relatively simple, but there is no actual example on the wiki.  I eventually just had to try something out that I thought would work rather than being spoon fed someone else's example.  Since the internet is no place for having to figure things out yourself I'll post the actual code I used.

Since the bookmarklet can be quite long I stored it in a variable first.  Since javascript ignores whitespace like a sensible language I broke it up over multiple lines.  The actual code is just wrapped in a self invoking function for reasons I still don't really understand.

showcode = "javascript:(function() {"+
"var results = document.getElementsByClassName('"+prevurl+"');"+
"for (i=0; i "document.getElementById('show"+prevurl+"').style.display = 'none';"+
"; } )()";

Pasting that into something with syntax highlighting will show that prevurl is a variable, and outside the double quotes.  Everything else is inside.  This function is then called by just making the variable the destination of a onclick event.  If you want to see more the source is on the script's page.

With this, my script is, at the risk of tooting my own horn, quite good.  It is probably the only thing I've ever made that doesn't look like it was made by a 5 year old.

No comments:

Post a Comment