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:

  1. //this bool would be toggled by the network status of the Air application
  2. private var online:Boolean = true;
  3.  
  4. //called when the application first initializes
  5. private function init():void
  6. {
  7. // store a copy of the original XMLHttpRequest::open method
  8. // all built-in objects are properties of the domWindow object available in an mx:Html view
  9.  
  10. // being a prototypal language you can access the original version
  11. // of any instance method via the prototype property
  12. var original:Function = mailView.domWindow.XMLHttpRequest.prototype.open;
  13.  
  14. //new lets make our own version of 'open'
  15. var improved:Function = function(...args):void
  16. {
  17. //are we currently online?
  18. if( online )
  19. {
  20. // yes?
  21. // now we need to override the onreadystatechange function
  22. // so we can store the result of the request
  23. var onready:Function = this.onreadystatechange;
  24.  
  25. this.onreadystatechange = function(){
  26. // if there was originally an onready function
  27. // call it
  28. if( onready) onready.apply(this, arguments);
  29.  
  30. // this is where we would store the resulting information
  31. // to be retrieved when the application has connectivity
  32. };
  33.  
  34. // yay, closures...I know not cool in AS3, memory bloat
  35. // but com'on, its so quick
  36. original.apply(this,args);
  37. }
  38. else
  39. {
  40. // no?
  41. // retrieve the last saved data for this url
  42. // imagine some SQL here
  43. }
  44. };
  45.  
  46. //overwrite the original method with our new and improved hotness
  47. mailView.domWindow.XMLHttpRequest.prototype.open = improved;
  48. }

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

1 Comment

  1. devi | September 15th, 2012

    i want to retrieve the data’s from database table and display to next activity…. plz help me!!

Post a Comment