Sunday, May 27, 2012

Assembly to JavaScript;TSRs to Bookmarklets

Back when I started computing (the nineties), the coolest thing to to know was assembly. If you knew assembly you could make the computer do anything because the computer was essentially executing assembly[1].

Back in those days the way to inject code into the system was something called a Terminate And Stay Resident (TSR). This mini application could be invoked via a hotkey and run arbitrary code in your memory space - this was a great way to hack applications, or provide additional capabilities to programs.

Luckily history repeats itself.  Today, assembly has been replace by JavaScript, and  the mechanism for  TSRs is called bookmarklets. Bookmarklets are book marks which execute arbitrary javascript code.

To show you the power of bookmarklets I wrote a JavaScript bookmarklet that will take a search from  bing and run it on google or vice versa. You can install it by dragging SwapSearchEngine to your bookmark bar and then clicking on it.  I've embedded a video showing the bookmarklet in use.

If you'd like to play with bookmarklets the code is below and also available @ bitbucket.
javascript:function swapSearchEngine() {
 /* Test cases:
  1) do a google search - run bookmarklet
  2) do a bing search - run bookmarklet
  3) Go to a random page - run bookmarklet - make sure error occurs.

    /* Find page title. */
    var title = document.getElementsByTagName('title')[0].innerText;
    var errorMessage = "Only works on a Google or Bing search";

    /* search engine format is title="search term - Search Engine" */
    var searchEngineIndex = title.lastIndexOf(" - ");

    if (searchEngineIndex == -1) {

    var currentSearchEngine = title.substring(searchEngineIndex + 3);
    var newSearchLocation = "";
    if (currentSearchEngine == "Google Search") {
        newSearchLocation = "";
    } else if (currentSearchEngine == "Bing") {
        newSearchLocation = "";
    } else {

    var searchTerms = title.substring(0, searchEngineIndex);
    var newURL = newSearchLocation + "/search?q=" + escape(searchTerms);
    window.location = newURL;

 [1] Technically the computer didn't execute assembly, but there was a 1:1 mapping between assembly and what the computer executes.

No comments: