Friday, August 17, 2012

air: injecting jQuery

After you load a web page into an HTML component you may want to select, modify, add and remove DOM elements in reponse to events within the AIR application and/or gather data from the web page for use in the AIR app. jQuery ( http://jquery.com/ ) is a robust and feature filled JavaScript library which provides methods which can make it much easier to select and modify DOM elements, however not every web page includes this library and you may not have the option to modify the web page manually to add the jQuery library before loading it into your AIR application.

To work around this you can inject the library after the page has loaded, and then make calls to it's methods from within the AIR application. First you need to load the jQuery libary as a String. You can do this either from an online resource or from a copy of the JavaScript file on the hard drive, for example if you have included it as an asset within the application directory of the AIR app.

Here's an example of loading jQuery from a remote source:



And here's an example which loads jQuery from a JavaScript file saved as an asset in the application directory:



NOTE : To use these examples you will need to replace the dummy website URL and dummy class with real ones. They were developed in Flash Builder 4.5 but should be adaptable to Flex 3. This solution was inspired by an article by Brandon Martinez: http://www.brandonmartinez.com/2011/04/23/inject-jquery-onto-any-site/.

No comments:

Post a Comment