19 February 2009

Greasemonkey Search helper

Here is a handy Greasemonkey script: it allows you to search for the selected text in a background tab. This is useful because it won't distract from what you reading right now. And you have different keys are associated with different searches....

  • Alt-A - searches Amazon.com
  • Alt-G - search Google.com
  • Alt-W - searches Wikipedia.org
  • Alt-Y - searches YouTube.com
  • Alt-N - searches GoogleNews.com
  • Alt-R - searches RottenTomatoes.com

// ==UserScript==
// @name           Sri's Stuff
// @namespace      http://defcraft.org
// @description    Sri's Stuff
// @include        *
// ==/UserScript==

// Created-On: Jun 28, 2007
// Description:
//
// o Selection Search:
//   Make a selection and hit "G" or "A" to
//   search either Google or Amazon. Search opens
//   in background Tab.


(function () {
    
  function kpHandler(event) {
    var letter = String.fromCharCode(event.charCode);
    var sel = document.getSelection();

    if (!event.altKey || sel.length == 0)
      return;

    switch (letter) {
    case "a": case "Ã¥": // Alt-A
      doAmazonSearch(sel); 
      break;

    case "g": case "©": // Alt-G
      doGoogleSearch(sel);
      break;
      
    case "w": case "∑": // Alt-W
      doWikipediaSearch(sel);
      break;
      
    case "Â¥": // Alt-Y
      doYoutubeSearch(sel);
      break;
      
    case "˜": // Alt-N
      doGoogleNewsSearch(sel);
      break;
      
    case "®": // Alt-R
      doRottenTomatoesSearch(sel);
      break;
    }
  }


  // == User actions ============================
  
  function doRottenTomatoesSearch(sel) {
    var url = "http://www.rottentomatoes.com/" + 
              encodeURIComponent(sel);
    GM_openInTab(url);
  }
  
  function doGoogleNewsSearch(sel) {
    var url = "http://news.google.com/news?hl=en&ned=&q=" + 
              encodeURIComponent(sel) +
              "&btnG=Search+News";
    GM_openInTab(url);
  }
  
  function doYoutubeSearch(sel) {
    var url = "http://www.youtube.com/results?search_type=&search_query=" + 
              encodeURIComponent(sel) + "&aq=f";
    GM_openInTab(url);
  }
  
  function doWikipediaSearch(sel) {
    var url = "http://en.wikipedia.org/wiki/Special:Search?search=" +
              encodeURIComponent(sel) + "&sourceid=Mozilla-search";

    GM_openInTab(url);
  }

  function doAmazonSearch(sel) {
    var url = 'http://www.amazon.com/exec/obidos/external-search/' + 
              '?field-keywords=' + encodeURIComponent(sel) +
              '&mode=blended&tag=mozilla-20&sourceid=Mozilla-search';

    GM_openInTab(url);
  }


  function doGoogleSearch(sel) {
    var url = 'http://www.google.com/search?q=' +
              encodeURIComponent(sel) +
              '&ie=utf-8&oe=utf-8&aq=t' +
              '&rls=org.mozilla:en-US:official&client=firefox-a';

    GM_openInTab(url);
  }

  document.addEventListener('keypress',  kpHandler, false);

})();