August 19, 2011

building JavaScript mashups

Adding browser-independent features to websites ‘you did not build’ is possible - the only drawback is that the user must willingly choose to enable your mashup. Here’s one way to do it:

  1. develop a small mashup - whatever you want to build, minify it and wrap it in a closure like this: All this example does is to alert “Hello World” on the page it is executed on.

     (function(){
       alert('hello world');
     })();
    
  2. publish your minified JS file on a domain which you have access to (e.g. http://example.com/addon.min.js)

  3. add a browser favorite that injects a JavaScript tag into the current page, like this:

     javascript:( function() {
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = 'http://example.com/addon.min.js?' + (new Date().getTime());
       document.getElementsByTagName('body')[0].appendChild(script);
     })()
    

    Make sure to remove unnecessary whitespaces and to urlencode the entire string; otherwise, the execution won’t work. The result could look like this:

     javascript:(function()%7Bvar%20script=document.createElement('script');script.type='text/javascript';script.src='http://example.com/addon.min.js?'+(new%20Date().getTime());document.getElementsByTagName('body')%5B0%5D.appendChild(script);%7D)()
    

That’s it! Now you can visit any website you like, and execute your own mashup on it by clicking on the bookmark. You can even share it with other people, or sell it along a book (one good example on this is the DOM Monster).

Some things to watch out for:

  • Most browser will only allow GET cross site XMLHttpRequests and due to preflight change everything else into an OPTIONS request.

  • If you use JavaScript libraries like jQuery you should double check that all those extensions are only available inside your mashup, so they don’t interfere with the original website.

Happy hacking!

© Raphael Randschau 2010 - 2022 | Impressum