Modifying Webkit’s Window Object in Adobe Air

Webkit Air Logo

When most developers discuss the possibilities available with Adobe Air, they typically talk about moving from the web to desktop. While there is plenty of thing to be excited about there, today I’m going to discuss the possibility of using Adobe Air to extend the power the web. Specifically, I want to show you how to modify the global window object in Webkit (the HTML renderer in Air) so that you can add your own custom properties and method for use within your web applications.

Today’s example is how to create your own Ajax request cache to allow web applications to be run offline.
To kick this off, download theĀ project files and use them to create your own FlexBuilder project.

Open up the main application mxml document and you’ll see the following section minus the excessive inline comments:

//this bool would be toggled by the network status of the Air application
private var online:Boolean = true;

//called when the application first initializes
private function init():void
{
	// store a copy of the original XMLHttpRequest::open method
	// all built-in objects are properties of the domWindow object available in an mx:Html view

	// being a prototypal language you can access the original version
	// of any instance method via the prototype property
	var original:Function = mailView.domWindow.XMLHttpRequest.prototype.open;

	//new lets make our own version of 'open'
	var improved:Function = function(...args):void
	{
		//are we currently online?
		if( online )
		{
			// yes?
			// now we need to override the onreadystatechange function
			// so we can store the result of the request
			var onready:Function = this.onreadystatechange;

			this.onreadystatechange = function(){
			       // if there was originally an onready function
				   // call it
				   if( onready) onready.apply(this, arguments);

				// this is where we would store the resulting information
				// to be retrieved when the application has connectivity
			};

			// yay, closures...I know not cool in AS3, memory bloat
			// but com'on, its so quick
			original.apply(this,args);
		}
		else
		{
			// no?
                        // retrieve the last saved data for this url
			// imagine some SQL here
		}
	};

	//overwrite the original method with our new and improved hotness
	mailView.domWindow.XMLHttpRequest.prototype.open = improved;
}

Done. As simple as that.

With these fundamentals, you can modify any of the built-in functions in Webkit or create your own app-specific extensions to the browser.

Cheers,
Todd

Todd Cullen

Todd Cullen is a founder at ReignDesign.

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Share this post