I had earlier written a post on writing effective bookmarklets. Bookmarklets can perform a variety of useful tasks on the page, and here is a classic list of those useful bookmarklets.
Recently, I was asked to write a firefox extension that complemented a website I was working on, but evaluating the requirement, I realized nothing of the requirement needed much change in the browser chrome. I started writing this bookmarklet and it has now graduated to become a full blown application with server communication, user preferences, etc.
In this post, I thought of writing a little about the design of the server side communication in the bookmarklet application. Since the javascript code of the bookmarklet is embedded in the domain of the page, AJAX requests to our sever are not possible. Hence, we need to rely on cross domain server calls, and I used YUI GET for the purpose.
In the application, there was also a lot of HTML content that I had to render. The HTML and the CSS files for the page were supplied by the designer, and hence rendering by DOM Manipulation was out of question. Hence, I needed some way to fetch the HTML file from the server and render it inside the DIV at my bookmarklet created. I had to write a servlet to read the file from the server and send it across to the client. However, since the client was expecting only JSON (remember, the client server communication was done using YUI GET), the spaces and the quotations in the HTML file were throwing error.
Hence, the servlet that fetched the HTML file had to strip it of spaces and quotation marks, making it a valid JSON String. The issue however is complicated by the fact that the HTML files had JSP tags embedded in them. A simple file fetcher could not evaluate the tags. I then needed a way to evaluate the JSP and convert the resultant HTML to JSON String. There are two approaches possible, either write a server filter that does this, or write a tag library. I chose the latter for the obvious reason of maintainability and portability. I wrote a tag library that did exactly this and spit out the JSON String of the JSP that was processed. Here is the Tag defination and here, the Tag Handler. Hence, I have a way to render JSP pages on Bookmarklets easily. The Tag takes the name of the Javascript variable to which the JSON String converted from JSP will be assigned.