Making a web application mashable -- useable in another web page -- has some challenges in the area of cross-domain communications. Here is how I solved those problems for Zwibbler.com. (See the API demo here)

Zwibbler consists of a large javascript program and a little HTML. The javascript part uses Ajax methods to send POST requests back to the zwibbler.com server, to render some items without the limitations of the CANVAS tag. In particular, this allows it to support PDF output as well as SVG and PNG.

If you want to include Zwibbler.com on another web site, the zwibbler application still needs to communicate with zwibbler.com in order to perform these tasks. However, browsers will not allow this due to security restrictions. Javascript code can only communicate with the server that the main web page came from.

HTML allows you to embed one web page inside another, in the <iframe> element. They remain essentially separated. The container web site is only allowed to talk to its web server, and the iframe is only allowed to talk to its originating server. Furthermore, because they have different origins, the browser disallows any contact between the two frames. That includes function calls, and variable accesses.

A string to pass

The target's origin, or "*" to allow any origin.

But what if you want to get some data in between the two separate windows? For example, a zwibbler document might be a megabyte long when converted to a string. I want the containing web page to be able to get a copy of that string when it wants, so it can save it. Also, it should be able to access the saved PDF, PNG, or SVG image that the user produces. HTML5 provides a restricted way to communicate between different frames of the same window, called window.postMessage(). The postMessage function takes two parameters:

For example, to pass a message from the container web page to the iframe, we use:

iframe.contentWindow.postMessage("hello there", "http://zwibbler.com");

window.addEventListener("message", function( event ) { if ( event.data === "hello there" ) { // event.origin contains the host of the sending window. alert("Why, hello to you too, " + event.origin); } }, false );

Problem 1: Two way communication

The receiver of the message must have previously registered for an HTML event named "message". This event arrives via the same mechanism as mouse clicks.This method of communication is one way, but for a method call, we have to allow two way communication. We add a simple wrapper on top, called a Messenger, to allow two way communication. Each time you call a method in the iframe, you pass a reply function that is called with the results of that method call. We use JSON for the parameter marshalling.

The Messenger object must also keep track of how to direct the replies it receives. It assigns each request a unique ticket, and stores them in a table along with the reply function. When a reply with a matching ticket is recieved, the corresponding function is called:

Messenger.prototype = { init: function( targetFrame, targetDomain) { // The DOM node of the target iframe. this.targetFrame = targetFrame; // The domain, including http:// of the target iframe. this.targetDomain = targetDomain; // A map from ticket number strings to functions awaiting replies. this.replies = {}; this.nextTicket = 0; var self = this; window.addEventListener("message", function(e) { self.receive(e); }, false ); }, send: function( functionName, args, replyFn ) { var ticket = "ticket_" + (this.nextTicket++); var text = JSON.stringify( { "function": functionName, "args": args, "ticket": ticket }); if ( replyFn ) { this.replies[ticket] = replyFn; } this.targetFrame.postMessage( text, this.targetDomain ); },

receive: function( e ) { if ( e.origin !== this.targetDomain ) { // not for us: ignore. return; } var json; try { json = JSON.parse( e.data ); } catch(except) { alert( "Syntax error in response from " + e.origin + ": " + e.data ); return; } if ( !(json["ticket"] in this.replies ) ) { // no reply ticket. return; } var replyFn = this.replies[json["ticket"]]; delete this.replies[json["ticket"]]; var args = []; if ( "args" in json ) { args = json["args"]; } replyFn.apply( undefined, args ); },

Problem 2: Delayed loading

The receive function first checks the origin of the message. If it is not the one that we expected, then we ignore the message. Maybe it's from another iframe, such as an ad or a game that happens to be on the same page. It then checks to see if it has a ticket number. If so, it decodes the arguments and calls the associated reply function.There is one other complexity to handle. When we load the iframe, it takes some time to initialize before it is ready to receive events. If you send a message before it has registered to receive it, I'm not sure what happens, but it didn't work when I tried it.

So we have to add a bit of logic to the above code. When the iframe completes initializing, it sends a message consisting of the text "ready" to its parent window. If the Messenger is asked to send a message, and it has not yet received the "ready" message, then instead of sending it, it adds it to a queue for later. When it finally receives the ready message, it loops through the queue and finally sends all of the waiting messages to the iframe.

The complete code is contained in component.js