Start writing Javascript for GreaseMonkey (Firefox Extension)


January 21, 2009
If you're new to my website, why don't get my latest posts using RSS Feed or by Email.

another tip »

Firefox's one of the most popular browsers right now, and it's also the choice of most technician. Thank to its easy add-on system, there are already hundreds of add-ons on the internet. Despite the massive library of interesting add-ons on the internet, it's sometime still hard to find a simple extension fit for your need.

Well, no one know what you want more then yourself, so why not make your own extension. Firefox extension is quite easy moreover with the help of GreaseMonkey, your work couldn’t be any easier.

    GreaseMonkey allows you to customize the way a webpage displays using small bits of JavaScript. –GreaseMonkey in FireFox add-ons

That’s is all about GreaseMonkey. Simple but if using that properly, it could help you solve out a lot of problem.

Now, let’s start with a simple one. There are a paragraph with mix links and text and I want to extract the links out so I could import it into my download manager. It just take you 10 minutes for this simple one.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin venenatis, sapien vitae ullamcorper venenatis, mauris diam tempus ante, aliquam pretium felis mi ut augue. Curabitur imperdiet, sapien vel faucibus congue, sem ante commodo tellus, et blandit quam felis at risus. Morbi tristique quam vitae risus. Donec congue volutpat mauris. Nam tellus. Nullam nec velit. Nam congue. Mauris iaculis, nisl vel tincidunt euismod, neque enim mattis mauris, non porttitor velit tellus nec lorem. Donec sed purus nec diam congue rutrum. Aliquam erat volutpat. Nam condimentum mattis enim. Nam ut odio. Vestibulum vel ligula. Vestibulum mauris sapien, feugiat ac, ultrices in, feugiat non, tellus. Quisque aliquet, magna vitae dapibus mollis, est sem dictum nibh, eget congue nisl tortor at magna. Curabitur nec nisl at tellus mollis cursus. Fusce at metus.

You could download my script and try on your browser to see it in action.

First you need to install GreaseMonkey add-on here then restart browser.

Then install my script into your GreaseMonkey. Sorry for the mess up code at the end and it use jQuery so it’s quite different with what I wrote here.

Then select the example text above then press CTRL + ALT + L. It will display a modal dialog with the all the link in that paragraph.

LET’S DO IT

You could download the complete code here: Get Selected Links

Ok, let’s start make of like that (simplifier maybe).

Go to Tools/GreaseMonkey/New user script.

Type in the name and namespace the way you want. It’s not important anyways. Enter ‘*’ in included pages as you want your script run in all website.

It will ask you to choose an editor. Just use Notepad, it’s alright. I myself prefer NotePad++ though.

You will have a js file with some comment about it. Go to the end, type in “Alert(1);”, save. Go back to Firefox and press F5 see what happen

But we don’t want to fire an alert every time we go into a website, so delete it, only an experiment.

Now, we need to decide when you want to fire your code. My is when user press CTRL + ALT + L. So I add this code in the file.

The comment will explain itself.

//This function to add an event to an object
function addEvent( obj, type, fn )
{
    if (obj.addEventListener)
        obj.addEventListener( type, fn, false );
    else if (obj.attachEvent)
    {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
} 

//This will run everytime keydown trigger
window.GetSelectedLink =function(event)
{
    if(event.keyCode==76 && event.ctrlKey && event.altKey)
    {
    }
}
//Register GetSelectedLink to the document.onkeydown
addEvent(document, "keydown", window.GetSelectedLink);
class="bar">

      Now we need to get the selected text. As the script is only launch in FF so we don’t need to worry about other browser.

$(document).keyup(function(event){
    if(event.keyCode==76 && event.ctrlKey && event.altKey)
    {
        //Get the selection part
        //Cos we using firefox, don't need to care about IE :)
        var selection;
        var wrapper = document.createElement("span");
        var w = getSelection().getRangeAt(0);
        selection = w;
        w.surroundContents(wrapper);
        selection = wrapper.innerHTML;
        if(selection.length==0)
        {
            selection = $("body").html();
        }
    }
})

Filter the links out from the text;

result="";
while(selection.indexOf('href=')>=0)
{
    result +=selection.substring(selection.indexOf('href="')+6,selection.indexOf('"', selection.indexOf('href="')+6)) + "<br/>";
    result = result.replace(""http://linkblur.com/?","");">http://linkblur.com/?","");
    currentPos = selection.indexOf('"', selection.indexOf('href="')+6) + 1;
    selection = selection.substring(currentPos);
}

After this you should have the list of the link in the ‘result’ variable already. Add an  alert(result) to the end to see if is that correct.

The last part of my code is just me try to draw a form to display the result, which I think I should leave for you.

This post is just a very basic user script in Firefox but I hope I could give people who want to start with GreaseMonkey a starting point.

My next post will be about bring jQuery into GreaseMonkey. So see you next time.

  • Delicious
Under Category: GreaseMonkey
Article Tags:
Leave a Reply