Monday, January 9, 2012

Paste and Go - A Google Chrome extension

A functionality in browsers, specifically Google Chrome and Mozilla Firefox, which I find extremely comfortable is "Paste and Go".


This pastes in your clipboard contents in the address bar and submits it automatically at one go, which is a step less than pressing Paste and then submitting manually.

Because I like this functionality a lot, I decided to try and emulate it for input textboxes on websites with a Google Chrome extension.


Download

The extension is published at https://chrome.google.com/webstore/detail/nbilgjjflfiiijecdjpnbganoiafneph

And the source: https://github.com/dreasgrech/PasteAndGo

How it works

When invoking it (Right Click -> Paste and Go), the extension grabs reference to the input text box where you right clicked, clears its value and pastes in the contents of your clipboard.

It then searches for the closest <form> to your text box with jQuery's closest function and if it finds a form, it submits it.

Note that closest only traverses up the DOM tree, so it will not find <form>s which are either below (in the tree) or adjacent (siblings) to your input text box.

If no <form> is found, another approach is taken. This time, the extension searches for the closest button to your input text box and if it finds one, it clicks it. This time though, I couldn't use jQuery's closest since, most of the time, submit buttons in <form>s are placed after the input text box. Therefore, I wrote this function to find the 'closest' button:

var getClosestButton = function (el) {
        var buttons;
        while ((el = el.parent()).length) {
            buttons = el.find(":button, input[type=submit]"); // :button -> "input[type=button], button"

            if (buttons.length) {
                return buttons.eq(buttons.length - 1);
            }
        }
};

Once a button is found, a click event is simulated on it.

A word of caution

This extension may not always work as expected. This is because it assumes that the first <form> it finds closest (upwards only) to your input box is the correct form which needs to be submitted, or that the 'closest' button that's found near your input box is the button that needs to be clicked...and the extension may not always find the correct button or submit the correct form; although the later is very rarely an issue.

Therefore, use it at your own risk.

Here are some of the places where it worked successfully:
  • Facebook
  • docs.jquery.com
  • Stackoverflow
  • Twitter
  • Google
  • Yahoo!
  • Bing
  • YouTube
  • The Pirate Bay

And here are some of the sites in which it didn't work as expected:
  • Grooveshark
  • Gmail
  • CodePlex

Where did you try it, and did it work as expected?