If this guide is distributed with software that includes an end user agreement, this guide, as well as the software described in it, is furnished under license and
may be used or copied only in accordance with the terms of such license. Except as permitted by any such license, no part of this guide may be reproduced, stored
in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe
Systems Incorporated. Please note that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end
user license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Adobe
Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear in the informational
content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright law. The unauthorized
incorporation of such material into your new work could be a violation of the rights of the copyright owner. Please be sure to obtain any permission required
from the copyright owner.
Any references to company or person names in sample templates are for demonstration purposes only and are not intended to refer to any actual organization
or person.
Adobe, the Adobe logo, Acrobat, ActionScript, Adobe AIR, ColdFusion, Dreamweaver, Flash, Flex, Flex Builder, and Reader are either registered trademarks or
trademarks of Adobe Systems Incorporated in the United States and/or other countries.
Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Apple, Macintosh,
and Mac OS are trademarks of Apple Inc., registered in the United States and other countries. Java is a trademark or registered trademark of Sun Microsystems,
Inc. in the United States and other countries. Linux is the registered trademark of Linus Torvalds in the U.S. and other countries. All other trademarks are the
property of their respective owners.
This work is licensed under the Creative Commons Attribution Non-Commercial 3.0 License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc/3.0/us/
This product includes software developed by the Apache Software Foundation (http://www.apache.org/)
MPEG Layer-3 audio compression technology licensed by Fraunhofer IIS and Thomson Multimedia (http://www.mp3licensing.com).
Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com)
This product includes software developed by the OpenSymphony Group (http://www.opensymphony.com/)
This product contains either BSAFE and/or TIPEM software by RSA Security, Inc.
Sorenson Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
This product includes software developed by the IronSmith Project (http://www.ironsmith.org/).
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA.
Notice to U.S. Government End Users. The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of
“Commercial Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202,
as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and
Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights
as are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S. Government End Users, Adobe agrees to comply with all applicable
equal opportunity laws including, if appropriate, the provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment
Assistance Act of 1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1 through 60-60,
60-250, and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be incorporated by reference.
Use the following instructions to download and install the Windows®, Mac OS X, and Linux versions of AIR.
1
To update the runtime, a user must have administrative privileges for the computer.
Install the runtime on a Windows computer
1 Download the runtime installation file.
2 Double-click the runtime installation file.
3 In the installation window, follow the prompts to complete the installation.
Install the runtime on a Mac computer
1 Download the runtime installation file.
2 Double-click runtime installation file.
3 In the installation window, follow the prompts to complete the installation.
4 If the Installer displays an Authenticate window, enter your Mac OS user name and password.
Install the runtime on a Linux computer
1 Download the runtime installation file.
2 Set the file permissions so that the installer application can be executed:
From a command line, you can set the file permissions with the chmod +x installer.bincommand. Some
versions of Linux allow you to set the file permissions on the Properties dialog opened through a context menu.
3 Run the installer from the command line or by double-clicking the runtime installation file.
4 In the installation window, follow the prompts to complete the installation.
AIR is installed as either rpm or dpkg packages, with package names: adobeairv.n and adobecerts. Installation
requires a running X server. AIR registers the mime type:
installer-package+zip.
application/vnd.adobe.air-application-
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Removing Adobe AIR
Once you have installed the runtime, you can remove it using the following procedures.
Remove the runtime on a Windows computer
1 In the Windows Start menu, select Settings > Control Panel.
2 Select the Add or Remove Programs control panel.
3 Select “Adobe AIR” to remove the runtime.
4 Click the Change/Remove button.
Remove the runtime on a Mac computer
• Double-click the “Adobe AIR Uninstaller”, which is located in the /Applications/Utilities folder.
Remove the runtime on a Linux computer
Do one of the following:
• Select the “Adobe AIR Uninstaller” command from the Applications menu.
• Run the AIR installer binary with the -uninstall option
• Remove the AIR packages (adobeairv.n and adobecerts) with your package manager.
2
Adobe AIR installation
Installing and running the AIR sample applications
Some sample applications are available that demonstrate AIR features. You can access and install them using the
following instructions:
1 Download and run the AIR sample applications. The compiled applications as well as the source code are available.
2 To download and run a sample application, click the sample application Install Now button. You are prompted to
install and run the application.
3 If you choose to download sample applications and run them later, select the download links. You can run AIR
applications at any time by:
• On Windows, double-clicking the application icon on the desktop or selecting it from the Windows Start menu.
• On Mac OS, double-clicking the application icon, which is installed in the Applications folder of your user
directory (for example, in Macintosh HD/Users/JoeUser/Applications/) by default.
• On Linux, double-clicking the application icon on the desktop or selecting it from the Applications menu. AIR
applications are installed in their own folder under the
Note: Check the AIR release notes for updates to these instructions, which are located here:
http://www.adobe.com/go/learn_air_relnotes.
/opt directory.
Last updated12/9/2009
Chapter 2: Setting up HTML development
tools
To develop HTML-based Adobe® AIR® applications, you can use the Adobe®AIR® Extension for Dreamweaver, the AIR
SDK command-line tools, or other Web development tools that support Adobe AIR. This topic explains how to install
the Adobe AIR Extension for Dreamweaver and the AIR SDK.
Installing the AIR Extension for Dreamweaver
The AIR Extension for Dreamweaver helps you to create rich Internet applications for the desktop. For example, you
might have a set of web pages that interact with each other to display XML data. You can use the Adobe AIR Extension
for Dreamweaver to package this set of pages into a small application that can be installed on a user’s computer. When
the user runs the application from their desktop, the application loads and displays the website in its own application
window, independent of a browser. The user can then browse the website locally on their computer without an
Internet connection.
3
Dynamic pages such as Adobe® ColdFusion® and PHP pages won’t run in Adobe AIR. The runtime only works with
HTML and JavaScript. However, you can use JavaScript in your pages to call any web service exposed on the Internet—
including ColdFusion- or PHP-generated services—with Ajax methods such as XMLHTTPRequest or Adobe AIRspecific APIs.
For more information about the types of applications you can develop with Adobe AIR, see “Introducing Adobe AIR”
on page 6.
System requirements
To use the Adobe AIR Extension for Dreamweaver, the following software must be installed and properly configured:
• Dreamweaver CS3 or Dreamweaver CS4
• Adobe® Extension Manager CS3
• Java JRE 1.4 or later (necessary for creating the Adobe AIR file). The Java JRE is available at http://java.sun.com/.
The preceding requirements are only for creating and previewing Adobe AIR applications in Dreamweaver. To
install and run an Adobe AIR application on the desktop, you must also install Adobe AIR on your computer. To
download the runtime, see
www.adobe.com/go/air.
Install the Adobe AIR Extension for Dreamweaver
1 Download the Adobe AIR Extension for Dreamweaver here: http://www.adobe.com/products/air/tools/ajax/.
2 Double-click the .mxp extension file in Windows Explorer (Windows) or in the Finder (Macintosh).
3 Follow the onscreen instructions to install the extension.
4 After you’re finished, restart Dreamweaver.
For information about using the Adobe AIR Extension for Dreamweaver, see “Using the AIR Extension for
Dreamweaver” on page 18.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Setting up HTML development tools
Installing the AIR SDK
The Adobe AIR SDK contains the following command-line tools that you use to launch and package applications:
AIR Debug Launcher (ADL) Allows you to run AIR applications without having to first install them. See “Using the
AIR Debug Launcher (ADL)” on page 23.
AIR Development Tool (ADT) Packages AIR applications into distributable installation packages. See “Packaging an
AIR installation file using the AIR Developer Tool (ADT)” on page 25.
The AIR command-line tools require Java to be installed your computer. You can use the Java virtual machine from
either the JRE or the JDK (version 1.4 or newer). The Java JRE and the Java JDK are available at
Note: Java is not required for end users to run AIR applications.
Download and install the AIR SDK
You can download and install the AIR SDK using the following instructions:
Install the AIR SDK in Windows
1 Download the AIR SDK installation file.
2 The AIR SDK is distributed as a standard file archive. To install AIR, extract the contents of the SDK to a folder on
your computer (for example: C:\Program Files\Adobe\AIRSDK or C:\AIRSDK).
3 The ADL and ADT tools are contained in the bin folder in the AIR SDK; add the path to this folder to your PATH
environment variable.
http://java.sun.com/.
4
Install the AIR SDK in Mac OS X
1 Download the AIR SDK installation file.
2 The AIR SDK is distributed as a standard file archive. To install AIR, extract the contents of the SDK to a folder on
your computer (for example: /Users/<userName>/Applications/AIRSDK).
3 The ADL and ADT tools are contained in the bin folder in the AIR SDK; add the path to this folder to your PATH
environment variable.
For information about getting started using the AIR SDK tools, see “Creating an AIR application using the
command line tools” on page 23.
What's included in the AIR SDK
The following table describes the purpose of the files contained in the AIR SDK:
Last updated12/9/2009
SDK folderFiles/tools description
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Setting up HTML development tools
5
BINadl.exe - The AIR Debug Launcher (ADL) allows you to run an AIR application without first packaging and
FRAMEWORKSAIRAliases.js - Provides "alias" definitions that allow you to access the ActionScript runtime classes. For
LIBadt.jar - The adt executable file, which is called by the adt.bat file.
RUNTIMEThe AIR runtime - The runtime is used by ADL to launch your AIR applications before they have been packaged
SAMPLESThis folder contains a sample application descriptor file, a sample of the seamless install feature (badge.swf),
SRCThis folder contains the source files for the seamless install sample.
TEMPLATESdescriptor-template.xml - A template of the application descriptor file, which is required for each AIR
installing it. For information about using this tool, see
adt.bat - The AIR Developer Tool (ADT) packages your application as an AIR file for distribution. For
information about using this tool, see
on page 25.
information about using this alias file, see
servicemonitor.swf - Provides AIR applications with an event-based means of responding to changes in
network connectivity to a specified host. For information about using this framework, see
network connectivity” on page 339.
Descriptor.1.0.xsd - The application schema file.
or installed.
and the default AIR application icons; see
application. For a detailed description of the application descriptor file, see
properties” on page 116.
“Packaging an AIR installation file using the AIR Developer Tool (ADT)”
“Using the AIRAliases.js file” on page 58
“Distributing, Installing, and Running AIR applications” on page 360.
“Using the AIR Debug Launcher (ADL)” on page 23.
“Monitoring
“Setting AIR application
Last updated12/9/2009
Chapter 3: Introducing Adobe AIR
Adobe® AIR® is a cross-operating system runtime that allows you to leverage your existing web development skills
(Adobe® Flash® CS3 Professional, Adobe® Flash® CS4 Professional, Adobe® Flex™, Adobe® ActionScript® 3.0, HTML,
JavaScript®, Ajax) to build and deploy Rich Internet Applications (RIAs) to the desktop.
You can find more information about getting started with and using Adobe AIR at the Adobe AIR Developer
Connection (
AIR enables you to work in familiar environments, to leverage the tools and approaches you find most comfortable,
and by supporting Flash, Flex, HTML, JavaScript, and Ajax, to build the best possible experience that meets your needs.
For example, applications can be developed using one or a combination of the following technologies:
• Flash / Flex / ActionScript
• HTML / JavaScript / CSS / Ajax
• PDF can be leveraged with any application
As a result, AIR applications can be:
http://www.adobe.com/devnet/air/).
6
• Based on Flash or Flex: Application whose root content is Flash/Flex (SWF)
• Based on Flash or Flex with HTML or PDF. Applications whose root content is Flash/Flex (SWF) with HTML
(HTML, JS, CSS) or PDF content included
• HTML-based. Application whose root content is HTML, JS, CSS
• HTML-based with Flash/Flex or PDF. Applications whose root content is HTML with Flash/Flex (SWF) or PDF
content included
Users interact with AIR applications in the same way that they interact with native desktop applications. The runtime
is installed once on the user's computer, and then AIR applications are installed and run just like any other desktop
application.
The runtime provides a consistent cross-operating system platform and framework for deploying applications and
therefore eliminates cross-browser testing by ensuring consistent functionality and interactions across desktops.
Instead of developing for a specific operating system, you target the runtime, which has the following benefits:
• Applications developed for AIR run across multiple operating systems without any additional work by you. The
runtime ensures consistent and predictable presentation and interactions across all the operating systems
supported by AIR.
• Applications can be built faster by enabling you to leverage existing web technologies and design patterns and
extend your web based applications to the desktop without learning traditional desktop development technologies
or the complexity of native code.
• Application development is easier than using lower level languages such as C and C++. You do not need to manage
the complex, low-level APIs specific to each operating system.
When developing applications for AIR, you can leverage a rich set of frameworks and APIs:
• APIs specific to AIR provided by the runtime and the AIR framework
• ActionScript APIs used in SWF files and Flex framework (as well as other ActionScript based libraries and
frameworks)
• HTML, CSS and JavaScript
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Introducing Adobe AIR
• Most Ajax frameworks
AIR dramatically changes how applications can be created, deployed, and experienced. You gain more creative control
and can extend your Flash, Flex, HTML, and Ajax-based applications to the desktop, without learning traditional
desktop development technologies.
What’s new in AIR 1.1
Adobe AIR 1.1 introduced the following new capabilities:
• Installation and other runtime dialog boxes have been translated into:
• Brazilian Portuguese
• Chinese (Traditional and Simplified)
• French
• German
• Italian
• Japanese
• Korean
• Russian
• French
• Spanish
• Support for building internationalized applications, including keyboard input for double-byte languages. See
“Localizing AIR applications” on page 395.
• Support for localizing the name and description attributes in the application descriptor file.
• Support for localizing error messages, such as SQLError.detailID and SQLError.detailArguments, in the SQLite
database.
• Addition of Capabilities.languages property to obtain an array of preferred UI languages as set by the operating
system.
• HTML button labels and default menus, such as context menus and the Mac menu bar, have been localized to
all supported languages.
• Support for certificate migration from a self-signed application to one that chains to a certificate of authority (CA).
• Support for Microsoft Windows XP Tablet PC Edition and support for 64-bit editions of Windows Vista® Home
Premium, Business, Ultimate, or Enterprise.
• Addition of File.spaceAvailable API to obtain the amount of disk space available on a disk.
• Addition of NativeWindow.supportsTransparency property to determine whether a window can be drawn as
transparent by the current operating system.
For more information about the AIR 1.1 release, see the Adobe AIR 1.1 Release Notes
http://www.adobe.com/go/learn_air_relnotes_en).
(
7
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Introducing Adobe AIR
What’s new in AIR 1.5
Adobe AIR 1.5 introduces the following new features:
• Support for the following features of Flash Player 10.
• Custom Filters and Effects
• Enhanced Drawing API
• Dynamic Sound Generation
• Vector Data Type
• Enhanced file upload and download APIs
• Real Time Media Flow Protocol (RTMFP)
• 3D Effects
• Advanced Text Support
• Color Management
• Text Engine
• Dynamic Streaming
• Speex Audio Codec
For more information, see http://www.adobe.com/products/flashplayer/features/ for details of these features.
8
• Additional languages supported in the AIR 1.5 installer and other runtime dialog boxes: Czech, Dutch, Swedish,
Turkish, Polish.
• Database encryption.
Database files can be encrypted in AIR 1.5. All database content, including the metadata, can be encrypted so that
the data is unreadable outside of the AIR application that encrypted it. This feature will allow a developer to
encrypt, decrypt, and re-encrypt database files. See
“Storing encrypted data” on page 290.
• The version of WebKit used by Adobe AIR has been updated and it now includes support for the SquirrelFish
JavaScript interpreter.
• New XML signature validation APIs that can be used to help verify the integrity and signer identity of data or
information. See
For more information about the AIR 1.5 release, see the Adobe AIR 1.5 Release Notes
http://www.adobe.com/go/learn_air_relnotes_en).
(
“XML signature validation” on page 406.
Last updated12/9/2009
Chapter 4: Finding AIR Resources
For more information on developing Adobe® AIR® applications, see the following resources:
SourceLocation
Adobe AIR Language Reference for HTML Developershttp://www.adobe.com/go/learn_air_html_jslr_en
Adobe AIR Quick Starts for HTMLhttp://www.adobe.com/go/learn_air_html_qs_en
You can find articles, samples and presentations by both Adobe and community experts on the Adobe AIR Developer
Connection at
there.
You can find a section specifically for HTML and Ajax developers at http://www.adobe.com/devnet/air/ajax/.
Visit the Adobe Support website, at http://www.adobe.com/support/, to find troubleshooting information for your
product and to learn about free and paid technical support options. Follow the Training link for access to Adobe Press
books, a variety of training resources, Adobe software certification programs, and more.
http://www.adobe.com/devnet/air/. You can also download Adobe AIR and related software from
9
Last updated12/9/2009
Chapter 5: Creating your first HTMLbased AIR application with the AIR SDK
For a quick, hands-on illustration of how Adobe® AIR® works, use these instructions to create and package a simple
HTML-based AIR “Hello World” application.
To begin, you must have installed the runtime and set up the AIR SDK. You will use the AIR Debug Launcher (ADL)
and the AIR Developer Tool (ADT) in this tutorial. ADL and ADT are command-line utility programs and can be
found in the
assumes that you are already familiar with running programs from the command line and know how to set up the
necessary path environment variables for your operating system.
Create the project files
Every HTML-based AIR project must contain the following two files: an application descriptor file, which specifies the
application metadata, and a top-level HTML page. In addition to these required files, this project includes a JavaScript
code file,
bin directory of the AIR SDK (see “Setting up HTML development tools” on page 3). This tutorial
AIRAliases.js, that defines convenient alias variables for the AIR API classes.
10
To begin:
1 Create a directory named HelloWorld to contain the project files.
2 Create an XML file, named HelloWorld-app.xml.
3 Create an HTML file named HelloWorld.html.
4 Copy AIRAliases.js from the frameworks folder of the AIR SDK to the project directory.
Create the AIR application descriptor file
To begin building your AIR application, create an XML application descriptor file with the following structure:
2 Add the root <application> element, including the AIR namespace attribute:
<application xmlns="http://ns.adobe.com/air/application/1.5"> The last segment of the namespace, “1.5”,
specifies the version of the runtime required by the application.
Last updated12/9/2009
3 Add the <id> element:
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating your first HTML-based AIR application with the AIR SDK
<id>examples.html.HelloWorld</id> The application id uniquely identifies your application along with the
publisher id (which AIR derives from the certificate used to sign the application package). The recommended form
is a dot-delimited, reverse-DNS-style string, such as
"com.company.AppName". The application id is used for
installation, access to the private application file-system storage directory, access to private encrypted storage, and
interapplication communication.
4 Add the <version> element:
<version>0.1</version> Helps users to determine which version of your application they are installing.
5 Add the <filename> element:
<filename>HelloWorld</filename> The name used for the application executable, install directory, and other
references to the application in the operating system.
6 Add the <initialWindow> element containing the following child elements to specify the properties for your
initial application window:
<content>HelloWorld.html</content> Identifies the root HTML file for AIR to load.
<visible>true</visible> Makes the window visible immediately.
<width>400</width> Sets the window width (in pixels).
11
<height>200</height> Sets the window height.
7 Save the file. The completed application descriptor file should look like the following:
This example only sets a few of the possible application properties. For the full set of application properties, which
allow you to specify such things as window chrome, window size, transparency, default installation directory,
associated file types, and application icons, see
“Setting AIR application properties” on page 116.
Create the application HTML page
You now need to create a simple HTML page to serve as the main file for the AIR application.
1 Open the HelloWorld.html file for editing. Add the following HTML code:
AIR defines a property named runtime on the HTML window object. The runtime property provides access to the
built-in AIR classes, using the fully qualified package name of the class. For example, to create an AIR File object
you could add the following statement in JavaScript:
var textFile = new runtime.flash.filesystem.File("app:/textfile.txt");
The AIRAliases.js file defines convenient aliases for the most useful AIR APIs. Using AIRAliases.js, you could
shorten the reference to the File class to the following:
var textFile = new air.File("app:/textfile.txt");
3 Below the AIRAliases script tag, add another script tag containing a JavaScript function to handle the onLoad event:
<script type="text/javascript">
function appLoad(){
air.trace("Hello World");
}
</script>
12
The appLoad() function simply calls the air.trace() function. The trace message print to the command console
when you run the application using ADL. Trace statements can be very useful for debugging.
4 Save the file.
Your HelloWorld.html file should now look like the following:
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating your first HTML-based AIR application with the AIR SDK
Test the application
To run and test the application from the command line, use the AIR Debug Launcher (ADL) utility. The ADL
executable can be found in the
up HTML development tools” on page 3.
❖ First, open a command console or shell. Change to the directory you created for this project. Then, run the
following command:
adl HelloWorld-app.xml
An AIR window opens, displaying your application. Also, the console window displays the message resulting from
air.trace() call.
the
For more information, see “Using the AIR Debug Launcher (ADL)” on page 23.
bin directory of the AIR SDK. If you haven’t already set up the AIR SDK, see “Setting
Create the AIR installation file
When your application runs successfully, you can use the ADT utility to package the application into an AIR
installation file. An AIR installation file is an archive file that contains all the application files, which you can distribute
to your users. You must install Adobe AIR before installing a packaged AIR file.
13
To ensure application security, all AIR installation files must be digitally signed. For development purposes, you can
generate a basic, self-signed certificate with ADT or another certificate generation tool. You can also buy a commercial
code-signing certificate from a commercial certificate authority such as VeriSign or Thawte. When users install a selfsigned AIR file, the publisher is displayed as “unknown” during the installation process. This is because a self-signed
certificate only guarantees that the AIR file has not been changed since it was created. There is nothing to prevent
someone from self-signing a masquerade AIR file and presenting it as your application. For publicly released AIR files,
a verifiable, commercial certificate is strongly recommended. For an overview of AIR security issues, see
security” on page 100.
Generate a self-signed certificate and key pair
❖ From the command prompt, enter the following command (the ADT executable is located in the bin directory of
ADT generates a keystore file named sampleCert.pfx containing a certificate and the related private key.
This example uses the minimum number of attributes that can be set for a certificate. You can use any values for
the parameters in italics. The key type must be either 1024-RSA or 2048-RSA (see
page 369).
Create the AIR installation file
❖ From the command prompt, enter the following command (on a single line):
You will be prompted for the keystore file password.
The HelloWorld.air argument is the AIR file that ADT produces. HelloWorld-app.xml is the application descriptor
file. The subsequent arguments are the files used by your application. This example only uses two files, but you can
include any number of files and directories.
After the AIR package is created, you can install and run the application by double-clicking the package file. You
can also type the AIR filename as a command in a shell or command window.
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating your first HTML-based AIR application with the AIR SDK
Next Steps
In AIR, HTML and JavaScript code generally behaves the same as it would in a typical web browser. (In fact, AIR uses
the same WebKit rendering engine used by the Safari web browser.) However, there are some important differences
that you must understand when you develop HTML applications in AIR. For more information on these differences,
and other important topics, see:
14
Last updated12/9/2009
Chapter 6: Create your first HTML-based
AIR application with Dreamweaver
For a quick, hands-on illustration of how Adobe® AIR® works, use these instructions to create and package a simple
HTML-based AIR “Hello World” application using the Adobe® AIR® Extension for Dreamweaver®.
If you haven’t already done so, download and install Adobe AIR , which is located here: www.adobe.com/go/air.
For instructions on installing the Adobe AIR Extension for Dreamweaver, see “Installing the AIR Extension for
Dreamweaver” on page 3.
For an overview of the extension, including system requirements, see “Using the AIR Extension for Dreamweaver” on
page 18.
Prepare the application files
15
Your Adobe AIR application must have a start page and all of its related pages defined in a Dreamweaver site. (For
more information on Dreamweaver sites, see Dreamweaver Help.) To create a start page for a simple "Hello World"
AIR application, follow these instructions:
1 Start Dreamweaver and make sure you have a site defined.
2 Open a new HTML page by selecting File > New, selecting HTML in the Page Type column, selecting None in the
Layout column, and clicking Create.
3 In the new page, type Hello World!
This example is extremely simple, but if you want you can style the text to your liking, add more content to the page,
link other pages to this start page, and so on.
4 Save the page (File > Save) as hello_world.html. Make sure you save the file in a Dreamweaver site.
Create the Adobe AIR application
1 Make sure you have the hello_world.html page open in the Dreamweaver Document window. (See the previous
section for instructions on creating it.)
2 Select Site > Air Application Settings.
Most of the required settings in the AIR Application and Settings dialog box are auto-populated for you. You must,
however, select the initial content (or start page) of your application.
3 Click the Browse button next to the Initial Content option, navigate to your hello_world.html page, and select it.
4 Next to the Digital signature option, click the Set button.
A digital signature provides an assurance that the code for an application has not been altered or corrupted since
its creation by the software author, and is required on all Adobe AIR applications.
5 In the Digital Signature dialog box, select Sign the AIR package with a digital certificate, and click the Create button.
(If you already have access to a digital certificate, you can click the Browse button to select it instead.)
Last updated12/9/2009
6 Complete the required fields in the Self-Signed Digital Certificate dialog box. You’ll need to enter your name, enter
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Create your first HTML-based AIR application with Dreamweaver
a password and confirm it, and enter a name for the digital certificate file. Dreamweaver saves the digital certificate
in your site root.
7 Click OK to return to the Digital Signature dialog box.
8 In the Digital Signature dialog box, enter the password you specified for your digital certificate and click OK.
Your completed AIR Application and Installer Settings dialog box might look like this:
16
For further explanation about all of the dialog box options and how to edit them, see “Creating an AIR application
in Dreamweaver” on page 18.
9 Click the Create AIR File button.
Dreamweaver creates the Adobe AIR application file and saves it in your site root folder. Dreamweaver also creates
an application.xml file and saves it in the same place. This file serves as a manifest, defining various properties of
the application.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Create your first HTML-based AIR application with Dreamweaver
Install the application on a desktop
Now that you’ve created the application file, you can install it on any desktop.
1 Move the Adobe AIR application file out of your Dreamweaver site and onto your desktop, or to another desktop.
This step is optional. You can actually install the new application on your computer right from your Dreamweaver
site directory if you prefer.
2 Double-click the application executable file (.air file) to install the application.
Preview the Adobe AIR application
You can preview pages that will be part of AIR applications at any time. That is, you don’t necessarily need to package
the application before seeing what it will look like when it’s installed.
1 Make sure your hello_world.html page is open in the Dreamweaver Document window.
2 On the Document toolbar, click the Preview/Debug in Browser button, and then select Preview In AIR.
You can also press Ctrl+Shift+F12 (Windows) or Cmd+Shift+F12 (Macintosh).
17
When you preview this page, you are essentially seeing what a user would see as the start page of the application
after they’ve installed the application on a desktop.
Last updated12/9/2009
Chapter 7: Using the AIR Extension for
Dreamweaver
The Adobe® AIR® Extension for Dreamweaver® lets you transform a web-based application into a desktop application.
Users can then run the application on their desktops and, in some cases, without an Internet connection.
You can use the extension with Dreamweaver CS3 and Dreamweaver CS4. It is not compatible with Dreamweaver 8.
For information about installing the extension, see “Installing the AIR Extension for Dreamweaver” on page 3.
Note: Adobe AIR does not support Adobe InContext Editing. If you use the AIR Extension for Dreamweaver to export
an application that contains InContext Editing regions, the InContext Editing functionality will not work.
Creating an AIR application in Dreamweaver
To create an HTML-based AIR application in Dreamweaver, you select an existing site to package as an AIR
application.
18
1 Make sure that the web pages you want to package into an application are contained in a defined Dreamweaver site.
2 In Dreamweaver, open the home page of the set of pages you want to package.
3 Select Site > Air Application Settings.
4 Complete the AIR Application and Installer Settings dialog box, and then click Create AIR File.
For more information, see the dialog box options listed below.
The first time you create an Adobe AIR file, Dreamweaver creates an application.xml file in your site root folder.
This file serves as a manifest, defining various properties of the application.
The following describes the options in the AIR Application and Installer Settings dialog box:
Application File Name is the name used for the application executable file. By default, the extension uses the name
of the Dreamweaver site to name the file. You can change the name if you prefer. However, the name must contain
only valid characters for files or folder names. (That is, it can only contain ASCII characters, and cannot end with
a period.) This setting is required.
Application Name is the name that appears on installation screens when users install the application. Again, the
extension specifies the name of the Dreamweaver site by default. This setting does not have character restrictions,
and is not required.
Application ID identifies your application with a unique ID. You can change the default ID if you prefer. Do not
use spaces or special characters in the ID. The only valid characters are 0-9, a-z, A-Z, . (dot), and - (dash). This
setting is required.
Version specifies a version number for your application. This setting is required.
Initial Content specifies the start page for your application. Click the Browse button to navigate to your start page
and select it. The chosen file must reside inside the site root folder. This setting is required.
Description lets you specify a description of the application to display when the user installs the application.
Last updated12/9/2009
Copyright lets you specify a copyright that is displayed in the About information for Adobe AIR applications
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Using the AIR Extension for Dreamweaver
installed on the Macintosh. This information is not used for applications installed on Windows.
Window Style specifies the window style (or chrome) to use when the user runs the application on their computer.
System chrome surrounds the application with the operating system standard window control. Custom chrome
(opaque) eliminates the standard system chrome and lets you create a chrome of your own for the application. (You
build the custom chrome directly in the packaged HTML page.) Custom chrome (transparent) is like Custom
chrome (opaque), but adds transparent capabilities to the edges of the page, allowing for application windows that
are not rectangular in shape.
Window Size specifies the dimensions of your application window when it opens.
Icon lets you select custom images for the application icons. (The default images are Adobe AIR images that come
with the extension.) To use custom images, click the Select Icon Images button. Then, in the Icon Images dialog
box that appears, click the folder for each icon size and select the image file you want to use. AIR only supports PNG
files for application icon images.
Note: Selected custom images must reside in the application site, and their paths must be relative to the site root.
Associated File Types lets you associate file types with your application. For more information, see the section that
follows.
Application Updates determines whether the Adobe AIR Application Installer or the application itself performs
updates to new versions of Adobe AIR applications. The check box is selected by default, which causes the Adobe
AIR Application Installer to perform updates. If you want your application to perform its own updates, deselect the
checkbox. Keep in mind that if you deselect the checkbox, you then need to write an application that can perform
updates.
19
Included Files specifies which files or folders to include in your application. You can add HTML and CSS files,
image files, and JavaScript library files. Click the Plus (+) button to add files, and the folder icon to add folders. You
should not include certain files such as _mmServerScripts, _notes, and so on. To delete a file or folder from your
list, select the file or folder and click the Minus (-) button.
Digital Signature Click Set to sign your application with a digital signature. This setting is required. For more
information, see the section that follows.
Program Menu Folder specifies a subdirectory in the Windows Start Menu where you want the application’s
shortcut created. (Not applicable on Macintosh.)
Destination specifies where to save the new application installer (.air file). The default location is the site root. Click
the Browse button to select a different location. The default file name is based on the site name with an .air
extension added to it. This setting is required.
Last updated12/9/2009
The following is an example of the dialog box with some basic options set:
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
20
Using the AIR Extension for Dreamweaver
Signing an application with a digital certificate
A digital signature provides an assurance that the code for an application has not been altered or corrupted since its
creation by the software author. All Adobe AIR applications require a digital signature, and can’t be installed without
one. You can sign your application with a purchased digital certificate, create your own certificate, or prepare an Adobe
AIRI file (an Adobe AIR intermediate file) that you’ll sign at a later time.
1 In the AIR Application and Installer Settings dialog box, click the Set button next to the Digital Signature option.
2 In the Digital Signature dialog box, do one of the following:
• To sign an application with a pre-purchased digital certificate, click the Browse button, select the certificate,
enter the corresponding password, and click OK.
• To create your own self-signed digital certificate, click the Create button and complete the dialog box. The
certificate Type option refers to the level of security: 1024-RSA uses a 1024-bit key (less secure), and 2048-RSA
uses a 2048-bit key (more secure). When you’re finished click OK. Then enter the corresponding password in
the Digital Signature dialog box and click OK.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Using the AIR Extension for Dreamweaver
• Select Prepare an AIRI package that will be signed later and click OK. This option lets you create an AIR
Intermediate (AIRI) application without a digital signature. A user is not able to install the application, however,
until you add a digital signature.
About Timestamping
When you sign an Adobe AIR application with a digital certificate, the packaging tool queries the server of a timestamp
authority to obtain an independently verifiable date and time of signing. The timestamp obtained is embedded in the
AIR file. As long as the signing certificate is valid at the time of signing, the AIR file can be installed, even after the
certificate has expired. On the other hand, if no timestamp is obtained, the AIR file ceases to be installable when the
certificate expires or is revoked.
By default, the Adobe AIR Extension for Dreamweaver obtains a timestamp when creating an Adobe AIR application.
You can, however, turn timestamping off by deselecting the Timestamp option in the Digital Signature dialog box.
(You might want to do this, for example, if a timestamping service is unavailable.) Adobe recommends that all
publically distributed AIR files include a timestamp.
The default timestamp authority used by the AIR packaging tools is Geotrust. For more information on timestamping
and digital certificates, see
21
Editing associated AIR file types
You can associate different file types with your Adobe AIR application. For example, if you want file types with an .avf
extension to open in Adobe AIR when a user double-clicks them, you can add the .avf extension to your list of
associated file types.
1 In the AIR Application and Installer Settings dialog box, click the Edit list button next to the Associated File Types
option.
2 In the Associated File Types dialog box, do one of the following:
• Select a file type and click the minus (-) button to delete the file type.
• Click the plus (+) button to add a file type.
If you click the plus button to add a file type, the File Type Settings dialog box appears. Complete the dialog box
and click OK to close it.
Following is a list of options:
Name specifies the name of the file type that appears in the Associated File Types list. This option is required,
and can only include alphanumeric ASCII characters (a-z, A-Z, 0-9) and dots (for example, adobe.VideoFile).
The name must start with a letter. The maximum length is 38 characters.
Extension specifies the extension of the file type. Do not include a preceding dot. This option is required, and
can only include alphanumeric ASCII characters (a-z, A-Z, 0-9). The maximum length is 38 characters.
Description lets you specify an optional description for the file type.
Content Type specifies the MIME type or media type for the file (for example text/html, image/gif, and so on).
Icon File Locations lets you select custom images for the associated file types. (The default images are Adobe
AIR images that come with the extension.)
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Using the AIR Extension for Dreamweaver
Editing AIR application settings
You can edit the settings for your Adobe AIR application at any time.
❖ Select Site > AIR Application Settings and make your changes.
Previewing a web page in an AIR application
You can preview an HTML page in Dreamweaver as it would appear in an Adobe AIR application. Previewing is useful
when you want to see what a web page will look like in the application without having to create the entire application.
❖ On the Document toolbar, click the Preview/Debug in Browser button, and then select Preview In AIR.
You can also press Ctrl+Shift+F12 (Windows) or Cmd+Shift+F12 (Macintosh).
Using AIR code hinting and code coloring
The Adobe AIR Extension for Dreamweaver also adds code hinting and code coloring for Adobe AIR language
elements in Code view in Dreamweaver.
22
• Open an HTML or JavaScript file in Code view and enter Adobe AIR code.
Note: The code hinting mechanism only works inside <script> tags, or in .js files.
For more information on the Adobe AIR language elements, see the developer documentation in the rest of this
guide.
Accessing the Adobe AIR documentation
The Adobe AIR extension adds a Help menu item in Dreamweaver that lets you access Developing AIR Applications
with HTML and Ajax.
❖ Select Help > Adobe AIR Help.
More Help topics
“Create your first HTML-based AIR application with Dreamweaver” on page 15
Last updated12/9/2009
Chapter 8: Creating an AIR application
using the command line tools
The Adobe® AIR® command line tools allow you to test and package Adobe AIR applications. You can also use these
tools in automated build processes. The command line tools are included in both the Adobe® Flex™ and AIR SDKs.
Using the AIR Debug Launcher (ADL)
Use the AIR Debug Launcher (ADL) to run both SWF-based and HTML-based applications during development.
Using ADL, you can run an application without first packaging and installing it. By default, ADL uses a runtime
included with the SDK, which means you do not have to install the runtime separately to use ADL.
ADL prints trace statements and run-time errors to the standard output, but does not support breakpoints or other
debugging features. If you're developing a SWF-based application, use the Flash Debugger for complex debugging issues.
You can connect to the Flash Debugger by starting the debugger program before running your application with ADL.
-runtime runtime-directory Specifies the directory containing the runtime to use. If not specified, the runtime
directory in the same SDK as the ADL program is used. If you move ADL out of its SDK folder, then you must specify
the runtime directory. On Windows and Linux, specify the directory containing the
OS X, specify the directory containing
-pubid publisher-id Assigns the specified value as the publisher ID of the AIR application for this run. Specifying a
temporary publisher ID allows you to test features of an AIR application, such as communicating over a local
connection, that use the publisher ID to help uniquely identify an application. As of AIR 1.5.3, you can also specify the
publisher ID in the application descriptor file (and should not use this parameter).
Note: As of AIR 1.5.3, a Publisher ID is no longer automatically computed and assigned to an AIR application. You can
specify a publisher ID when creating an update to an existing AIR application, but new applications do not need and
should not specify a publisher ID.
-nodebug Turns off debugging support. If used, the application process cannot connect to the Flash debugger and
dialogs for unhandled exceptions are suppressed. (However, trace statements still print to the console window.)
Turning off debugging allows your application to run a little faster and also emulates the execution mode of an
installed application more closely.
application.xml The application descriptor file. See “Setting AIR application properties” on page 116.
Adobe AIR.framework.
Adobe AIR directory. On Mac
root-directory Specifies the root directory of the application to run. If not specified, the directory containing the
application descriptor file is used.
-- arguments Any character strings appearing after "--" are passed to the application as command line arguments.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
Note: When you launch an AIR application that is already running, a new instance of that application is not started.
Instead, an
invoke event is dispatched to the running instance.
Printing trace statements
To print trace statements to the console used to run ADL, add trace statements to your code with the air.trace()
function:
In JavaScript, you can use the alert() and confirm() functions to display debugging messages from your
application. In addition, the line numbers for syntax errors as well as any uncaught JavaScript exceptions are printed
to the console.
ADL Examples
Run an application in the current directory:
adl myApp-app.xml
Run an application in a subdirectory of the current directory:
24
adl source/myApp-app.xml release
Run an application and pass in two command line arguments, "tick" and "tock":
adl myApp-app.xml -- tick tock
Run an application using a specific runtime:
adl -runtime /AIRSDK/runtime myApp-app.xml
Run an application without debugging support:
adl myApp-app.xml -nodebug
Connecting to the Flash Debugger (FDB)
To debug an HTML-based AIR application with the Flash Debugger, start an FDB session and then launch the
application using ADL.
1 Start FDB. The FDB program can be found in the bin directory of the Flex SDK.
The console displays the FDB prompt: <fdb>
The Flex SDK is available from http://opensource.adobe.com.
2 Execute the run command: <fdb>run [Enter]
3 In a different command or shell console, start a debug version of your application:
adl myApp.xml
4 Using the FDB commands, set breakpoints as desired.
5 Type: continue [Enter]
If an AIR application is SWF-based, the debugger only controls the execution of ActionScript code. If the AIR
application is HTML-based, then the debugger only controls the execution of JavaScript code.
To run ADL without connecting to the debugger, include the -nodebug option:
Last updated12/9/2009
adl myApp.xml -nodebug
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
For basic information on FDB commands, execute the help command:
<fdb>help [Enter]
For details on the FDB commands, see Using the command-line debugger commands in the Flex documentation.
ADL exit and error codes
The following table describes the exit codes printed by ADL:
Exit codeDescription
0Successful launch. ADL exits after the AIR application exits.
1Successful invocation of an already running AIR application. ADL exits immediately.
2Usage error. The arguments supplied to ADL are incorrect.
3The runtime cannot be found.
25
4The runtime cannot be started. Often, this occurs because the version or patch level specified in the
5An error of unknown cause occurred.
6The application descriptor file cannot be found.
7The contents of the application descriptor are not valid. This error usually indicates that the XML is not
8The main application content file (specified in the <content> element of the application descriptor file)
9The main application content file is not a valid SWF or HTML file.
application does not match the version or patch level of the runtime.
well formed.
cannot be found.
Packaging an AIR installation file using the AIR
Developer Tool (ADT)
You create an AIR installation file for both your SWF-based and HTML-based AIR applications using the AIR
Developer Tool (ADT). (If you are using the Adobe® AIR® Extension for Dreamweaver® to create your application, you
can also use the Create AIR File command on the AIR Application and Installer Settings dialog to build the AIR
package. See
ADT is a Java program that you can run from the command line or a build tool such as Ant. The SDK includes
command line scripts that execute the Java program for you. See
information on configuring your system to run the ADT tool.
“Using the AIR Extension for Dreamweaver” on page 18.)
“Setting up HTML development tools” on page 3 for
Packaging an AIR installation file
Every AIR application must, at a minimum, have an application descriptor file and a main SWF or HTML file. Any
other installed application assets must be packaged in the AIR file as well.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
All AIR package files must be signed using a digital certificate. The AIR installer uses the signature to verify that your
application file has not been altered since you signed it. You can use a code signing certificate from a certification
authority or a self-signed certificate. A certificate issued by a trusted certification authority provides users of your
application some assurance of your identity as publisher. A self-signed certificate cannot be used to verify your identity
as the signer. This drawback also weakens the assurance that the package hasn’t been altered, because a legitimate
installation file could be substituted with a forgery before it reaches the user.
You can package and sign an AIR file in a single step using the ADT -package command. You can also create an
intermediate, unsigned package with the
-prepare command, and sign the intermediate package with the -sign
command in a separate step.
When signing the installation package, ADT automatically contacts a time-stamp authority server to verify the time.
The time-stamp information is included in the AIR file. An AIR file that includes a verified time stamp can be installed
at any point in the future. If ADT cannot connect to the time-stamp server, then packaging is canceled. You can
override the time-stamping option, but without a time stamp, an AIR application ceases to be installable after the
certificate used to sign the installation file expires.
If you are creating a package to update an existing AIR application, the package must be signed with the same
certificate as the original application. If the original certificate has been renewed or has expired within the last 180 days,
or if you want to change to a new certificate, you can apply a migration signature. A migration signature involves
signing the application AIR file with both the new and the old certificate. Use the
migration signature as described in
“Signing an AIR file to change the application certificate” on page 35.
-migrate command to apply the
26
Important: There is a strict 180 day grace period for applying a migration signature after the original certificate expires.
Without a migration signature, existing users must uninstall their existing application before installing your new version.
The grace period only applies to applications that specify AIR version 1.5.3, or above, in the application descriptor
namespace. There is no grace period when targeting earlier versions of the AIR runtime.
Prior to AIR 1.1, migration signatures were not supported. You must package an application with an SDK of version
1.1 or later to apply a migration signature.
Publisher IDs
As of AIR 1.5.3, publisher IDs are deprecated. New applications (originally published with AIR 1.5.3 or later) do not
need and should not specify a publisher ID.
When updating applications published with earlier versions of AIR, you must specify the original publisher ID in the
application descriptor file. Otherwise, the installed version of your application and the update version are treated as
different applications. If you use a different ID or omit the publisherID tag, a user must uninstall the earlier version
before installing the new version.
To determine the original publisher ID, find the publisherid file in the META-INF/AIR subdirectory where the
original application is installed. The string within this file is the publisher ID. Your application descriptor must specify
the AIR 1.5.3 runtime (or later) in the namespace declaration of the application descriptor file in order to specify the
publisher ID manually.
For applications published prior to AIR 1.5.3 — or that are published with the AIR 1.5.3 SDK, while specifying an
earlier version of AIR in the application descriptor namespace — a publisher ID is computed based on the signing
certificate. This ID is used, along with the application ID, to determine the identity of an application. The publisher
ID, when present, is used for the following purposes:
• Verifying that an AIR file is an update rather than a new application to install
• As part of the encryption key for the encrypted local store
• As part of the path for the application storage directory
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
• As part of the connection string for local connections
• As part of the identity string used to invoke an application with the AIR in-browser API
• As part of the OSID (used when creating custom install/uninstall programs)
Before AIR 1.5.3, the publisher ID of an application could change if you signed an application update with migration
signature using a new or renewed certificate. When a publisher ID changes, the behavior of any AIR features relying
on the ID also changes. For example, data in the existing encrypted local store can no longer be accessed and any Flash
or AIR instances that create a local connection to the application must use the new ID in the connection string.
In AIR 1.5.3, or later, the publisher ID is not based on the signing certificate and is only assigned if the publisherID tag
is included in the application descriptor. An application cannot be updated if the publisher ID specified for the update
AIR package does not match its current publisher ID.
Package and sign an AIR file in one step
❖ Use the -package command with the following syntax (on a single command line):
adt -package SIGNING_OPTIONS air_file app_xml [file_or_dir | -C dir file_or_dir | -e file
dir ...] ...
SIGNING_OPTIONS The signing options identify the keystore containing the private key and certificate used to
sign the AIR file. To sign an AIR application with a self-signed certificate generated by ADT, the options to use are:
27
-storetype pkcs12 -keystore certificate.p12
In this example, certificate.p12 is the name of the keystore file. (ADT prompts you for the password since it is not
supplied on the command line.) The signing options are fully described in
“ADT command line signing options”
on page 32.
air_file The name of the AIR file that is created.
app_xml The path to the application descriptor file. The path can be specified relative to the current directory or
as an absolute path. (The application descriptor file is renamed as “application.xml” in the AIR file.)
file_or_dir The files and directories to package in the AIR file. Any number of files and directories can be specified,
delimited by whitespace. If you list a directory, all files and subdirectories within, except hidden files, are added to
the package. (In addition, if the application descriptor file is specified, either directly, or through wildcard or
directory expansion, it is ignored and not added to the package a second time.) Files and directories specified must
be in the current directory or one of its subdirectories. Use the
-C option to change the current directory.
Important: Wild cards cannot be used in the file_or_dir arguments following the –C option. (Command shells
expand the wildcards before passing the arguments to ADT, which causes ADT to look for files in the wrong location.)
You can, however, still use the dot character, ".", to stand for the current directory. For example, "
-C assets ." copies
everything in the assets directory, including any subdirectories, to the root level of the application package.
-C dir Changes the working directory to the value of dir before processing subsequent files and directories added
to the application package. The files or directories are added to the root of the application package. The –
C option
can be used any number of times to include files from multiple points in the file system. If a relative path is specified
dir, the path is always resolved from the original working directory.
for
As ADT processes the files and directories included in the package, the relative paths between the current directory
and the target files are stored. These paths are expanded into the application directory structure when the package
is installed. Therefore, specifying
release/bin/lib/feature.swf in the lib subdirectory of the root application folder.
-e file dir Places the specified file into the specified package directory.
-C release/bin lib/feature.swf places the file
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
Note: The <content> element of the application descriptor file must specify the final location of the main application
file within the application package directory tree.
ADT Examples
Package specific application files in the current directory:
Note: The keystore file contains the private key used to sign your application. Never include the signing certificate inside
the AIR package! If you use wildcards in the ADT command, place the keystore file in a different location so that it is not
included in the package. In this example the keystore file, cert.p12, resides in the parent directory.
Package only the main files and an images subdirectory:
Package assets from more than one place in your build file system. In this example, the application assets are located
in the following folders before packaging:
The following tables list the possible errors that can be reported by the ADT program and the probable causes:
Application descriptor validation errors
Last updated12/9/2009
Error codeDescriptionNotes
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
30
100Application descriptor cannot be parsedCheck the application descriptor file for
101Namespace is missingAdd the missing namespace.
102Invalid namespaceCheck the namespace spelling.
103Unexpected element or attributeRemove offending elements and attributes.
104Missing element or attributeAdd the required element or attribute.
105Element or attribute contains an invalid
value
106Illegal window attribute combinationSome window settings, such as
107Window minimum size is larger than the
window maximum size
XML syntax errors such as unclosed tags.
Custom values are not allowed in the
descriptor file.
Check the spelling of element and attribute
names.
Make sure that elements are placed within
the correct parent element and that
attributes are used with the correct
elements.
Correct the offending value.
transparency = true and
systemChrome = standard cannot be
used together. Change one of the
incompatible settings.
Change either the minimum or the
maximum size setting.
See “Setting AIR application properties” on page 116 for a information about the namespaces, elements, attributes, and
their valid values.
Application icon errors
Error codeDescriptionNotes
200Icon file cannot be openedCheck that the file exists at the specified
201Icon is the wrong sizeIcon size (in pixels) must match the XML
202Icon file contains an unsupported image
format
path.
Use another application to ensure that the
file can be opened.
tag. For example, given the application
descriptor element:
<image32x32>icon.png</image32x3
2>
The image in icon.png must be exactly
32x32 pixels.
Only the PNG format is supported. Convert
images in other formats before packaging
your application.
Application file errors
Last updated12/9/2009
Error codeDescriptionNotes
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
31
300Missing file, or file cannot be openedA file specified on the command line
301Application descriptor file missing or
cannot be opened
302Root content file missing from packageThe SWF or HTML file referenced in the
303Icon file missing from packageThe icon files specified in the application
304Initial window content is invalid The file referenced in the <content>
305Initial window content SWF version
exceeds namespace version
cannot be found, or cannot be opened.
The application descriptor file cannot be
found at the specified path or cannot
opened.
<content> element of the application
descriptor must be added to the package
by including it in the files listed on the ADT
command line.
descriptor must be added to the package
by including them among the files listed on
the ADT command line. Icon files are not
added automatically.
element of the application descriptor is not
recognized as a valid HTML or SWF file.
The SWF version of the file referenced in
<content> element of the application
the
descriptor is not supported by the version
of AIR specified in the descriptor
namespace. For example, attempting to
package a SWF10 (Flash Player 10) file as
the initial content of an AIR 1.1 application
will generate this error.
Exit codes for other errors
Exit codeDescriptionNotes
2Usage errorCheck the command line arguments for
5Unknown errorThis error indicates a situation that cannot
6Could not write to output directoryMake sure that the specified (or implied)
7Could not access certificateMake sure that the path to the keystore is
8Invalid certificateThe certificate file is malformed, modified,
9Could not sign AIR fileVerify the signing options passed to ADT.
errors
be explained by common error conditions.
Possible root causes include
incompatibility between ADT and the Java
Runtime Environment, corrupt ADT or JRE
installations, and programming errors
within ADT.
output directory is accessible and that the
containing drive is has sufficient disk space.
specified correctly.
Check that the certificate within the
keystore can be accessed. The Java 1.6
Keytool utility can be used to help
troubleshoot certificate access issues.
expired, or revoked.
Last updated12/9/2009
Exit codeDescriptionNotes
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
32
10Could not create time stampADT could not establish a connection to the
11Certificate creation errorVerify the command line arguments used
12Invalid inputVerify file paths and other arguments
timestamp server. If you connect to the
internet through a proxy server, you may
need to configure the JRE proxy settings.
for creating signatures.
passed to ADT on the command line.
ADT command line signing options
ADT uses the Java Cryptography Architecture (JCA) to access private keys and certificates for signing AIR
applications. The signing options identify the keystore and the private key and certificate within that keystore.
The keystore must include both the private key and the associated certificate chain. The certificate chain is used to
establish the publisher ID for the application. If the signing certificate chains to a trusted certificate on a computer,
then the common name of the certificate is displayed as the publisher name on the AIR installation dialog.
ADT requires that the certificate conform to the x509v3 standard (RFC3280) and include the Extended Key Usage
extension with the proper values for code signing. Constraints within the certificate are respected and could preclude
the use of some certificates for signing AIR applications.
Note: ADT uses the Java runtime environment proxy settings, when appropriate, for connecting to Internet resources for
checking certificate revocation lists and obtaining time-stamps. If you encounter problems connecting to Internet
resources when using ADT and your network requires specific proxy settings, you may need to configure the JRE proxy
settings.
Specifying AIR signing options
❖ To specify the ADT signing options for the -package and -prepare commands, use the following syntax:
-alias aliasName —The alias of a key in the keystore. Specifying an alias is not necessary when a keystore only
contains a single certificate. If no alias is specified, ADT uses the first key in the keystore.
Not all keystore management applications allow an alias to be assigned to certificates. When using the Windows
system keystore for example, use the distinguished name of the certificate as the alias. You can use the Java Keytool
utility to list the available certificates so that you can determine the alias. For example, running the command:
keytool -list -storetype Windows-MY
produces output like the following for a certificate:
To reference this certificate on the ADT command line, set the alias to:
Last updated12/9/2009
CN=TestingCert,OU=QE,O=Adobe,C=US
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
On Mac OS X, the alias of a certificate in the Keychain is the name displayed in the Keychain Access application.
-storetype type —The type of keystore, determined by the keystore implementation. The default keystore
implementation included with most installations of Java supports the
support for the
OS X keychain. Java 6.0 includes support for the
PKCS11 type, for accessing keystores on hardware tokens, and Keychain type, for accessing the Mac
MSCAPI type (on Windows). If other JCA providers have been
JKS and PKCS12 types. Java 5.0 includes
installed and configured, additional keystore types might be available. If no keystore type is specified, the default
type for the default JCA provider is used.
33
Store typeKeystore formatMinimum Java
JKSJava keystore file (.keystore)1.2
PKCS12PKCS12 file (.p12 or .pfx)1.4
PKCS11Hardware token1.5
KeychainStoreMac OS X Keychain1.5
Windows-MY or
Windows-ROOT
MSCAPI1.6
version
-keystore path —The path to the keystore file for file-based store types.
-storepass password1 —The password required to access the keystore. If not specified, ADT prompts for the
password.
-keypass password2 —The password required to access the private key that is used to sign the AIR application. If
not specified, ADT prompts for the password.
-providerName className —The JCA provider for the specified keystore type. If not specified, then ADT uses the
default provider for that type of keystore.
-tsa url —Specifies the URL of an RFC3161-compliant timestamp server to time-stamp the digital signature. If no
URL is specified, a default time-stamp server provided by Geotrust is used. When the signature of an AIR
application is time-stamped, the application can still be installed after the signing certificate expires, because the
timestamp verifies that the certificate was valid at the time of signing.
If ADT cannot connect to the time-stamp server, then signing is canceled and no package is produced. Specify -
tsa none to disable time-stamping. However, an AIR application packaged without a timestamp ceases to be
installable after the signing certificate expires.
Note: The signing options are like the equivalent options of the Java Keytool utility. You can use the Keytool utility to
examine and manage keystores on Windows. The Apple® security utility can also be used for this purpose on Mac OS X.
Creating an unsigned AIR intermediate file with ADT
Use the -prepare command to create an unsigned AIR intermediate file. An AIR intermediate file must be signed with
the ADT
The -prepare command takes the same flags and parameters as the -package command (except for the signing
options). The only difference is that the output file is not signed. The intermediate file is generated with the filename
extension:
-sign command to produce a valid AIR installation file.
airi.
34
To sign an AIR intermediate file, use the ADT -sign command. (See Signing an AIR intermediate file with ADT.)
For more information, see “Digitally signing an AIR file” on page 369.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
Signing an AIR file to change the application certificate
To publish an update for an existing AIR application while using a new or renewed signing certificate, use the ADT -
migrate command to apply a certificate migration signature. A migration signature is a second signature applied to
an AIR file using the original certificate. The migration signature validates that an application update was produced
by the owners of the original certificate.
In order to apply a migration signature, the original certificate must still be valid or have expired within the last 180
days. Once the certificate has expired and the 180 day grace period has elapsed, a migration signature cannot be
applied. Users of your application will have to uninstall the existing version before they can install the updated version.
The migration signature is time stamped, by default, so AIR updates signed with a migration signature will remain
valid even after the certificate expires.
Note: The 180 day grace period only applies to applications specifying AIR version 1.5.3, or higher, in the application
descriptor namespace.
To migrate the application to use a new or renewed certificate:
1 Create an update to your application
2 Package and sign the update AIR file with the new certificate
3 Sign the AIR file again with the original certificate using the -migrate command
An AIR file signed with the -migrate command can be used both to install a new version of the application and to
update any previous versions, including those signed with the old certificate.
35
Note: When updating an application published for a version of AIR earlier than1.5.3, you must specify the original
publisher ID in the application descriptor. Otherwise, users of your application must uninstall the earlier version before
installing the update.
Migrate an AIR application to use a new certificate
❖ Use the ADT -migrate command with following syntax:
SIGNING_OPTIONS The signing options identify the private key and certificate with which to sign the AIR file.
These options must identify the original signing certificate and are described in
“ADT command line signing
options” on page 32.
air_file_in The AIR file for the update, signed with the new certificate.
For more information, see “Digitally signing an AIR file” on page 369.
Note: The -migrate command was added to ADT in the AIR 1.1 release.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
Creating a self-signed certificate with ADT
Self-signed certificates allow you to produce a valid AIR installation file, but only provide limited security assurances
to your users since the authenticity of self-signed certificates cannot be verified. When a self-signed AIR file is installed,
the publisher information is displayed to the user as Unknown. A certificate generated by ADT is valid for five years.
If you create an update for an AIR application that was signed with a self-generated certificate, you must use the same
certificate to sign both the original and update AIR files. The certificates that ADT produces are always unique, even
if the same parameters are used. Thus, if you want to self-sign updates with an ADT-generated certificate, preserve the
original certificate in a safe location. In addition, you will be unable to produce an updated AIR file after the original
ADT-generated certificate expires. (You can publish new applications with a different certificate, but not new versions
of the same application.)
Important: Because of the limitations of self-signed certificates, Adobe strongly recommends using a commercial
certificate issued by a reputable certification authority for signing publicly released AIR applications.
The certificate and associated private key generated by ADT are stored in a PKCS12-type keystore file. The password
specified is set on the key itself, not the keystore.
Generating a digital ID certificate for self-signing AIR files
❖ Use the ADT -certificate command (on a single command line):
This topic provides examples of using the Apache Ant build tool to test and package AIR applications.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
Note: This discussion does not attempt to provide a comprehensive outline of Apache Ant. For Ant documentation, see
http://Ant.Apache.org.
Using Ant for simple projects
This example illustrates building an AIR application using Ant and the AIR command line tools. A simple project
structure is used with all files stored in a single directory.
To make it easier to reuse the build script, these examples use several defined properties. One set of properties
identifies the installed locations of the command line tools:
The second set of properties is project specific. These properties assume a naming convention in which the application
descriptor and AIR files are named based on the root source file. Other conventions are easily supported.
If your application has more files to package, you can add additional <arg> elements.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
Using Ant for more complex projects
The directory structure of a typical application is more complex than a single directory. The following example
illustrates a build file used to compile, test, and package an AIR application which has a more practical project
directory structure.
release This sample project stores application source files and other assets like icon files within a src directory. The
build script creates a release directory to store the final AIR package.
The AIR tools require the use of some additional options when operating on files outside the current working
directory:
Testing The second argument passed to ADL specifies the root directory of the AIR application. To specify the
application root directory, the following line is added to the testing task:
<arg value="${debug}"/>
Packaging Packaging files from subdirectories that should not be part of the final package structure requires using the
-C directive to change the ADT working directory. When you use the -C directive, files and directories in the new
working directory are copied to the root level of the AIR package file. Thus,
the root of the application directory. Likewise,
-C assets icons copies the icon folder to the root level, and copies
all the files and directories within the icons folder as well. For example, the following sequence of lines in the package
task adds the icons directory directly to the root level of the application package file:
Note: If you need to move many resources and assets into different relative locations, it is typically easier to marshall them
into a temporary directory using Ant tasks than it is to build a complex argument list for ADT. Once your resources are
organized, a simple ADT argument list can be used to package them.
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Creating an AIR application using the command line tools
39
Last updated12/9/2009
Chapter 9: Debugging with the AIR HTML
Introspector
The Adobe® AIR® SDK includes an AIRIntrospector.js JavaScript file that you can include in your application to help
debug HTML-based applications.
About the AIR Introspector
The Adobe AIR HTML/JavaScript Application Introspector (called the AIR HTML Introspector) provides useful
features to assist HTML-based application development and debugging:
• It includes an introspector tool that allows you to point to a user interface element in the application and see its
markup and DOM properties.
• It includes a console for sending objects references for introspection, and you can adjust property values and
execute JavaScript code. You can also serialize objects to the console, which limits you from editing the data. You
can also copy and save text from the console.
• It includes a tree view for DOM properties and functions.
• It lets you edit the attributes and text nodes for DOM elements.
• It lists links, CSS styles, images, and JavaScript files loaded in your application.
• It lets you view to the initial HTML source and the current markup source for the user interface.
• It lets you access files in the application directory. (This feature is only available for the AIR HTML Introspector
console opened for application sandbox. Not available for the consoles open for non-application sandbox content.)
• It includes a viewer for XMLHttpRequest objects and their properties, including responseText and responseXML
properties (when available).
• You can search for matching text in the source code and files.
40
Loading the AIR Introspector code
The AIR Introspector code is included in a JavaScript file, AIRIntrospector.js, that is included in the frameworks
directory of the AIR SDK. To use the AIR Introspector in your application, copy the AIRIntrospector.js to your
application project directory and load the file via a script tag in the main HTML file in your application:
Also include the file in every HTML file that corresponds to different native windows in your application.
Important: Include the AIRIntrospector.js file only when developing and debugging the application. Remove it in the
packaged AIR application that you distribute.
The AIRIntrospector.js file defines a class, Console, which you can access from JavaScript code by calling
air.Introspector.Console.
Note: Code using the AIR Introspector must be in the application security sandbox (in a file in the application directory).
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
Inspecting an object in the Console tab
The Console class defines five methods: log(), warn(), info(), error(), and dump().
The log(), warn(), info(), and error() methods all let you send an object to the Console tab. The most basic of
these methods is the
Console tab:
var test = "hello";
air.Introspector.Console.log(test);
However, it is more useful to send a complex object to the Console tab. For example, the following HTML page
includes a button (
<html>
<head>
<title>Source Viewer Sample</title>
<script type="text/javascript" src="scripts/AIRIntrospector.js"></script>
<script type="text/javascript">
function logBtn()
{
var button1 = document.getElementById("btn1");
air.Introspector.Console.log(button1);
}
</script>
</head>
<body>
<p>Click to view the button object in the Console.</p>
<input type="button" id="btn1"
onclick="logBtn()"
value="Log" />
</body>
</html>
log() method. The following code sends a simple object, represented by the test variable, to the
btn1) that calls a function that sends the button object itself to the Console tab:
41
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
When you click the button, the Console tab displays the btn1 object, and you can expand the tree view of the object to
inspect its properties:
42
You can edit a property of the object by clicking the listing to the right of the property name and modifying the text
listing.
The info(), error(), and warn() methods are just like the log() method. However, when you call these methods,
the Console displays an icon at the beginning of the line:
MethodIcon
info()
error()
warn()
The log(), warn(), info(), and error() methods send a reference only to an actual object, so the properties
available are the ones at the moment of viewing. If you want to serialize the actual object, use the
dump() method. The
method has two parameters:
ParameterDescription
dumpObjectThe object to be serialized.
levelsThe maximum number of levels to be examined in the object tree (in addition to the root level). The default
value is 1 (meaning that one level beyond the root level of the tree is shown). This parameter is optional.
Calling the dump() method serializes an object before sending it to the Console tab, so that you cannot edit the objects
properties. For example, consider the following code:
Last updated12/9/2009
var testObject = new Object();
testObject.foo = "foo";
testObject.bar = 234;
air.Introspector.Console.dump(testObject);
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
When you execute this code, the Console displays the testObject object and its properties, but you cannot edit the
property values in the Console.
Configuring the AIR Introspector
You can configure the console by setting properties of the global AIRIntrospectorConfig variable. For example, the
following JavaScript code configures the AIR Introspector to wrap columns at 100 characters:
var AIRIntrospectorConfig = new Object();
AIRIntrospectorConfig.wrapColumns = 100;
Be sure to set the properties of the AIRIntrospectorConfig variable before loading the AIRIntrospector.js file (via a
script tag).
There are eight properties of the AIRIntrospectorConfig variable:
43
PropertyDefault valueDescription
closeIntrospectorOnExittrueSets the Inspector window to close when all other windows of the
debuggerKey123 (the F12 key)The key code for the keyboard shortcut to show and hide the AIR
debugRuntimeObjectstrueSets the Introspector to expand runtime objects in addition to objects
flashTabLabelstrueSets the Console and XMLHttpRequest tabs to flash, indicating when a
introspectorKey122 (the F11 key)The key code for the keyboard shortcut to open the Inspect panel.
showTimestamptrueSets the Console tab to display timestamps at the beginning of each line.
showSendertrueSets the Console tab to display information on the object sending the
wrapColumns2000The number of columns at which source files are wrapped.
application are closed.
Introspector window.
defined in JavaScript.
change occurs in them (for example, when text is logged in these tabs).
message at the beginning of each line.
AIR Introspector interface
To open the AIR introspector window when debugging the application, press the F12 key or call one of the methods
of the Console class (see
key other than the F12 key; see “Configuring the AIR Introspector” on page 43.
“Inspecting an object in the Console tab” on page 41). You can configure the hot key to be a
Last updated12/9/2009
The AIR Introspector window has six tabs—Console, HTML, DOM, Assets, Source, and XHR—as shown in the
following illustration:
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
44
The Console tab
The Console tab displays values of properties passed as parameters to one of the methods of the
air.Introspector.Console class. For details, see
“Inspecting an object in the Console tab” on page 41.
• To clear the console, right-click the text and select Clear Console.
• To save text in the Console tab to a file, right-click the Console tab and select Save Console To File.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
• To save text in the Console tab to the clipboard, right-click the Console tab and select Save Console To Clipboard.
To copy only selected text to the clipboard, right-click the text and select Copy.
• To save text in the Console class to a file, right-click the Console tab and select Save Console To File.
• To search for matching text displayed in the tab, click CTRL+F on Windows or Command+F on Mac OS. (Tree
nodes that are not visible are not searched.)
The HTML tab
The HTML tab lets you view the entire HTML DOM in a tree structure. Click an element to view its properties on the
right-hand side of the tab. Click the + and - icons to expand and collapse a node in the tree.
45
You can edit any attribute or text element in the HTML tab and the edited value is reflected in the application.
Click the Inspect button (to the left of the list of tabs in the AIR Introspector window). You can click any element on
the HTML page of the main window and the associated DOM object is displayed in the HTML tab. When the main
window has focus, you can also press the keyboard shortcut to toggle the Inspect button on and off. The keyboard
shortcut is F11 by default. You can configure the keyboard shortcut to be a key other than the F11 key; see
the AIR Introspector” on page 43.
Click the Refresh Active Window button (at the top of the AIR Introspector window) to refresh the data displayed in
the HTML tab.
Click CTRL+F on Windows or Command+F on Mac OS to search for matching text displayed in the tab. (Tree nodes
that are not visible are not searched.)
“Configuring
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
The DOM tab
The DOM tab shows the window object in a tree structure. You can edit any string and numeric properties and the
edited value is reflected in the application.
46
Click the Refresh Active Window button (at the top of the AIR Introspector window) to refresh the data displayed in
the DOM tab.
Click CTRL+F on Windows or Command+F on Mac OS to search for matching text displayed in the tab. (Tree nodes
that are not visible are not searched.)
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
The Assets tab
The Assets tab lets you check the links, images, CSS, and JavaScript files loaded in the native window. Expanding one
of these nodes shows the content of the file or displays the actual image used.
47
Click the Refresh Active Window button (at the top of the AIR Introspector window) to refresh the data displayed in
the Assets tab.
Click CTRL+F on Windows or Command+F on Mac OS to search for matching text displayed in the tab. (Tree nodes
that are not visible are not searched.)
The Source tab
The Source tab includes three sections:
• Actual source—Shows the HTML source of the page loaded as the root content when the application started.
• Parsed source—Shows the current markup that makes up the application UI, which can be different from the actual
source, since the application generates markup code on the fly using Ajax techniques.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
• Application files—Lists the files in the application directory. This listing is only available for the AIR Introspector
when launched from content in the application security sandbox. In this section, you can view the content of text
files or view images.
48
Click the Refresh Active Window button (at the top of the AIR Introspector window) to refresh the data displayed in
the Source tab.
Click CTRL+F on Windows or Command+F on Mac OS to search for matching text displayed in the tab. (Tree nodes
that are not visible are not searched.)
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
The XHR tab
The XHR tab intercepts all XMLHttpRequest communication in the application and logs the information. This lets
you view the XMLHttpRequest properties including
responseText and responseXML (when available) in a tree view.
49
Click CTRL+F on Windows or Command+F on Mac OS to search for matching text displayed in the tab. (Tree nodes
that are not visible are not searched.)
Using the AIR Introspector with content in a nonapplication sandbox
You can load content from the application directory into an iframe or frame that is mapped to a non-application
sandbox (see
following rules:
• The AIRIntrospector.js file must be included in both the application sandbox and in the non-application sandbox
(the iframe) content.
• Do not overwrite the parentSandboxBridge property; the AIR Introspector code uses this property. Add
properties as needed. So instead of writing the following:
“HTML security” on page 106). You can use the AIR introspector with such content, but observe the
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Debugging with the AIR HTML Introspector
• From the non-application sandbox content, you cannot open the AIR Introspector by pressing the F12 key or by
calling one of methods in the air.Introspector.Console class. You can open the Introspector window only by
clicking the Open Introspector button. The button is added by default at the upper-right corner of the iframe or
frame. (Due to security restrictions imposed to non-application sandbox content, a new window can be opened
only as a result of a user gesture, such as clicking a button.)
• You can open separate AIR Introspector windows for the application sandbox and for the non-application
sandbox. You can differentiate the two using the title displayed in the AIR Introspector windows.
• The Source tab doesn’t display application files when the AIR Introspector is run from a non-application sandbox
• The AIR Introspector can only look at code in the sandbox from which it was opened.
50
Last updated12/9/2009
Chapter 10: Programming in HTML and
JavaScript
A number of programming topics are unique to developing Adobe® AIR® applications with HTML and JavaScript. The
following information is important whether you are programming an HTML-based AIR application or programming
a SWF-based AIR application that runs HTML and JavaScript using the HTMLLoader class (or mx:HTML Flex™
component).
Creating an HTML-based AIR application
The process of developing an AIR application is much the same as that of developing an HTML-based web application.
Application structure remains page-based, with HTML providing the document structure and JavaScript providing
the application logic. In addition, an AIR application requires an application descriptor file, which contains metadata
about the application and identifies the root file of the application.
51
If you are using Adobe® Dreamweaver®, you can test and package an AIR application directly from the Dreamweaver
user interface. If you are using the AIR SDK, you can test an AIR application using the command-line ADL utility.
ADL reads the application descriptor and launches the application. You can package the application into an AIR
installation file using the command-line ADT utility.
The basic steps to creating an AIR application are:
1 Create the application descriptor file. The content element identifies the root page of the application, which is
loaded automatically when your application is launched. (See
more information.)
2 Create the application pages and code.
3 Test the application using the ADL utility or Dreamweaver.
4 Package the application into an AIR installation file with the ADT utility or Dreamweaver.
For a walk-through of these steps, see “Creating your first HTML-based AIR application with the AIR SDK” on
page 10 or “Create your first HTML-based AIR application with Dreamweaver” on page 15.
“Setting AIR application properties” on page 116 for
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
An example application and security implications
In “Creating your first HTML-based AIR application with the AIR SDK” on page 10, the Hello World example is
intentionally simple. It only calls one AIR-specific API (the air.trace() method). The following HTML code uses a
more advanced AIR API; it uses the filesystem APIs to list the files and directories in the user’s desktop directory.
Here’s the HTML code for the application:
52
<html>
<head>
<title>Sample application</title>
<script type="text/javascript" src="AIRAliases.js"></script>
<script>
function getDesktopFileList()
{
var log = document.getElementById("log");
var files = air.File.desktopDirectory.getDirectoryListing();
for (i = 0; i < files.length; i++)
{
log.innerHTML += files[i].name + "<br/>";
}
}
</script>
</head>
<body onload="getDesktopFileList();" style="padding: 10px">
<h2>Files and folders on the desktop:</h2>
<div id="log" style="width: 450px; height: 200px; overflow-y: scroll;" />
</body>
</html>
You also must set up an application descriptor file and test the application using the AIR Debug Launcher (ADL)
application. (See
“Creating your first HTML-based AIR application with the AIR SDK” on page 10).
You could use most of the sample code in a web browser. However, there are a few lines of code that are specific to the
runtime.
The getDesktopFileList() method uses the File class, which is defined in the runtime APIs. The first script tag
in the application loads the AIRAliases.js file (supplied with the AIR SDK), which lets you easily access the AIR APIs.
(For example, the example code accesses the AIR File class using the syntax
air.File.) For details, see “Using the
AIRAliases.js file” on page 58.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
The File.desktopDirectory property is a File object (a type of object defined by the runtime). A File object is a
reference to a file or directory on the user’s computer. The
user’s desktop directory. The
File objects. The
File.desktopDirectory.getDirectoryListing() method returns an array of File objects
getDirectoryListing() method is defined for any File object and returns an array of
File.desktopDirectory property is a reference to the
representing files and directories on the user’s desktop.
Each File object has a name property, which is the filename as a string. The for loop in the getDesktopFileList()
method iterates through the files and directories on the user’s desktop directory and appends their names to the
innerHTML property of a div object in the application.
Important security rules when using HTML in AIR applications
The files you install with the AIR application have access to the AIR APIs. For security reasons, content from other
sources do not. For example, this restriction prevents content from a remote domain (such as http://example.com)
from reading the contents the user’s desktop directory (or worse).
Because there are security loopholes that can be exploited through calling the eval() function (and related APIs),
content installed with the application, by default, is restricted from using these methods. However, some Ajax
frameworks use the calling the
To properly structure content to work in an AIR application, you must take the rules for the security restrictions on
content from different sources into account. Content from different sources is placed in separate security
classifications, called sandboxes (see
installed in a sandbox known as the application sandbox, and this grants it access to the AIR APIs. The application
sandbox is generally the most secure sandbox, with restrictions designed to prevent the execution of untrusted code.
eval() function and related APIs.
“Sandboxes” on page 104). By default, content installed with the application is
53
The runtime allows you to load content installed with your application into a sandbox other than the application
sandbox. Content in non-application sandboxes operates in a security environment similar to that of a typical web
browser. For example, code in non-application sandboxes can use
eval() and related methods (but at the same time
is not allowed to access the AIR APIs). The runtime includes ways to have content in different sandboxes communicate
securely (without exposing AIR APIs to non-application content, for example). For details, see
“Cross-scripting
content in different security sandboxes” on page 63.
If you call code that is restricted from use in a sandbox for security reasons, the runtime dispatches a JavaScript error:
“Adobe AIR runtime security violation for JavaScript code in the application security sandbox.”
To avoid this error, follow the coding practices described in the next section, “Avoiding security-related JavaScript
errors” on page 53.
For more information, see “HTML security” on page 106.
Avoiding security-related JavaScript errors
If you call code that is restricted from use in a sandbox due to these security restrictions, the runtime dispatches a
JavaScript error: “Adobe AIR runtime security violation for JavaScript code in the application security sandbox.” To
avoid this error, follow these coding practices.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Causes of security-related JavaScript errors
Code executing in the application sandbox is restricted from most operations that involve evaluating and executing
strings once the document
following types of JavaScript statements that evaluate and execute potentially insecure strings generates JavaScript
errors:
• eval() function
• setTimeout() and setInterval()
• Function constructor
In addition, the following types of JavaScript statements fail without generating an unsafe JavaScript error:
• javascript: URLs
• Event callbacks assigned through onevent attributes in innerHTML and outerHTML statements
• Loading JavaScript files from outside the application installation directory
• document.write() and document.writeln()
• Synchronous XMLHttpRequests before the load event or during a load event handler
• Dynamically created script elements
Note: In some restricted cases, evaluation of strings is permitted. See “Code restrictions for content in different
sandboxes” on page 108 for more information.
load event has fired and any load event handlers have exited. Attempting to use the
54
Adobe maintains a list of Ajax frameworks known to support the application security sandbox, at
http://www.adobe.com/go/airappsandboxframeworks.
The following sections describe how to rewrite scripts to avoid these unsafe JavaScript errors and silent failures for
code running in the application sandbox.
Mapping application content to a different sandbox
In most cases, you can rewrite or restructure an application to avoid security-related JavaScript errors. However, when
rewriting or restructuring is not possible, you can load the application content into a different sandbox using the
technique described in
must access AIR APIs, you can create a sandbox bridge, as described in “Setting up a sandbox bridge interface” on
page 65.
“Loading application content into a non-application sandbox” on page 64. If that content also
eval() function
In the application sandbox, the eval() function can only be used before the page load event or during a load event
handler. After the page has loaded, calls to
rewrite your code to avoid the use of
eval() will not execute code. However, in the following cases, you can
eval().
Assigning properties to an object
Instead of parsing a string to build the property accessor:
eval("obj." + propName + " = " + val);
access properties with bracket notation:
obj[propName] = val;
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Creating a function with variables available in context
var _self = this;
this.appTimer = setInterval(function(){obj.customFunction.apply(_self);}, 100);
56
Function constructor
Calls to new Function(param, body) can be replaced with an inline function declaration or used only before the
load event has been handled.
page
javascript: URLs
The code defined in a link using the javascript: URL scheme is ignored in the application sandbox. No unsafe
JavaScript error is generated. You can replace links using javascript: URLs, such as:
<a href="javascript:code()">Click Me</a>
with:
<a href="#" onclick="code()">Click Me</a>
Event callbacks assigned through onevent attributes in innerHTML and
outerHTML statements
When you use innerHTML or outerHTML to add elements to the DOM of a document, any event callbacks assigned
within the statement, such as
assign an
addEventListener() method.
id attribute to the new elements and set the event handler callback functions using the
For example, given a target element in a document, such as:
<div id="container"></div>
onclick or onmouseover, are ignored. No security error is generated. Instead, you can
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Loading JavaScript files from outside the application installation directory
Loading script files from outside the application sandbox is not permitted. No security error is generated. All script
files that run in the application sandbox must be installed in the application directory. To use external scripts in a page,
you must map the page to a different sandbox. See
page 64.
“Loading application content into a non-application sandbox” on
document.write() and document.writeln()
Calls to document.write() or document.writeln() are ignored after the page load event has been handled. No
security error is generated. As an alternative, you can load a new file, or replace the body of the document using DOM
manipulation techniques.
Synchronous XMLHttpRequests before the load event or during a load event
handler
Synchronous XMLHttpRequests initiated before the page load event or during a load event handler do not return any
content. Asynchronous XMLHttpRequests can be initiated, but do not return until after the
event has been handled, synchronous XMLHttpRequests behave normally.
load event. After the load
57
Dynamically created script elements
Dynamically created script elements, such as when created with innerHTML or document.createElement()
method are ignored.
Accessing AIR API classes from JavaScript
In addition to the standard and extended elements of Webkit, HTML and JavaScript code can access the host classes
provided by the runtime. These classes let you access the advanced features that AIR provides, including:
• Access to the file system
• Use of local SQL databases
• Control of application and window menus
• Access to sockets for networking
• Use of user-defined classes and objects
• Sound capabilities
For example, the AIR file API includes a File class, contained in the flash.filesystem package. You can create a File
object in JavaScript as follows:
var myFile = new window.runtime.flash.filesystem.File();
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
The runtime object is a special JavaScript object, available to HTML content running in AIR in the application
sandbox. It lets you access runtime classes from JavaScript. The
access to the flash package. In turn, the
flash.filesystem property of the runtime object provides access to the
flash property of the runtime object provides
flash.filesystem package (and this package includes the File class). Packages are a way of organizing classes used in
ActionScript.
Note: The runtime property is not automatically added to the window objects of pages loaded in a frame or iframe.
However, as long as the child document is in the application sandbox, the child can access the
runtime property of the
parent.
Because the package structure of the runtime classes would require developers to type long strings of JavaScript
code strings to access each class (as in
window.runtime.flash.desktop.NativeApplication), the AIR SDK
includes an AIRAliases.js file that lets you access runtime classes much more easily (for instance, by simply typing
air.NativeApplication).
The AIR API classes are discussed throughout this guide. Other classes from the Flash Player API, which may be of
interest to HTML developers, are described in the Adobe AIR Language Reference for HTML Developers.
ActionScript is the language used in SWF (Flash Player) content. However, JavaScript and ActionScript syntax are
similar. (They are both based on versions of the ECMAScript language.) All built-in classes are available in both
JavaScript (in HTML content) and ActionScript (in SWF content).
Note: JavaScript code cannot use the Dictionary, XML, and XMLList classes, which are available in ActionScript.
58
Note: For more information, see “ActionScript 3.0 classes, packages, and namespaces” on page 128 and “ActionScript
basics for JavaScript developers” on page 126.
Using the AIRAliases.js file
The runtime classes are organized in a package structure, as in the following:
• window.runtime.flash.desktop.NativeApplication
• window.runtime.flash.desktop.ClipboardManager
• window.runtime.flash.filesystem.FileStream
• window.runtime.flash.data.SQLDatabase
Included in the AIR SDK is an AIRAliases.js file that provide “alias” definitions that let you access the runtime
classes with less typing. For example, you can access the classes listed above by simply typing the following:
• air.NativeApplication
• air.Clipboard
• air.FileStream
• air.SQLDatabase
This list is just a short subset of the classes in the AIRAliases.js file. The complete list of classes and package-level
functions is provided in the Adobe AIR Language Reference for HTML Developers.
In addition to commonly used runtime classes, the AIRAliases.js file includes aliases for commonly used packagelevel functions:
window.runtime.flash.net.sendToURL(), which are aliased as air.trace(), air.navigateToURL(), and
air.sendToURL().
window.runtime.trace(), window.runtime.flash.net.navigateToURL(), and
To use the AIRAliases.js file, include the following script reference in your HTML page:
<script src="AIRAliases.js"></script>
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Adjust the path in the src reference, as needed.
Important: Except where noted, the JavaScript example code in this documentation assumes that you have included
the AIRAliases.js file in your HTML page.
About URLs in AIR
In HTML content running in AIR, you can use any of the following URL schemes in defining src attributes for img,
frame, iframe, and script tags, in the href attribute of a link tag, or anywhere else you can provide a URL.
URL schemeDescriptionExample
59
fileA path relative to the root of the file system.
appA path relative to the root directory of the installed
application.
app-storageA path relative to the application store directory. For each
installed application, AIR defines a unique application store
directory, which is a useful place to store data specific to that
application.
httpA standard HTTP request.
httpsA standard HTTPS request.
file:///c:/AIR Test/test.txt
app:/images
app-storage:/settings/prefs.xml
http://www.adobe.com
https://secure.example.com
For more information about using URL schemes in AIR, see “Using AIR URL schemes in URLs” on page 344.
Many of AIR APIs, including the File, Loader, URLStream, and Sound classes, use a URLRequest object rather than a
string containing the URL. The URLRequest object itself is initialized with a string, which can use any of the same url
schemes. For example, the following statement creates a URLRequest object that can be used to request the Adobe
home page:
var urlReq = new air.URLRequest("http://www.adobe.com/");
For information about URLRequest objects see “URL requests and networking” on page 342.
Embedding SWF content in HTML
You can embed SWF content in HTML content within an AIR application just as you would in a browser. Embed the
SWF content using an
object tag, an embed tag, or both.
Note: A common web development practice is to use both an object tag and an embed tag to display SWF content in an
HTML page. This practice has no benefit in AIR. You can use the W3C-standard
displayed in AIR. At the same time, you can continue to use the
object and embed tags together, if necessary, for HTML
object tag by itself in content to be
content that is also displayed in a browser.
The following example illustrates the use of the HTML object tag to display a SWF file within HTML content. The
SWF file is loaded from the application directory, but you can use any of the URL schemes supported by AIR. (The
location from which the SWF file is loaded determines the security sandbox in which AIR places the content.)
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
You can also use a script to load content dynamically. The following example creates an object node to display the
SWF file specified in the
specified by the
<script>
function showSWF(urlString, elementID){
var displayContainer = document.getElementById(elementID);
displayContainer.appendChild(createSWFObject(urlString,650,650));
}
function createSWFObject(urlString, width, height){
urlString parameter. The example adds the node as a child of the page element with the ID
60
Using ActionScript libraries within an HTML page
AIR extends the HTML script element so that a page can import ActionScript classes in a compiled SWF file. For
example, to import a library named, myClasses.swf, located in the
include the following script tag within an HTML file:
Important: The type attribute must be type="application/x-shockwave-flash" for the library to be properly
loaded.
If the SWF content is compiled as a Flash Player 10 or AIR 1.5 SWF, you must set the XML namespace of the
application descriptor file to the AIR 1.5 namespace. For more information, see
descriptor file” on page 117.
The lib directory and myClasses.swf file must also be included when the AIR file is packaged.
Access the imported classes through the runtime property of the JavaScript Window object:
var libraryObject = new window.runtime.LibraryClass();
If the classes in the SWF file are organized in packages, you must include the package name as well. For example, if the
LibraryClass definition was in a package named utilities, you would create an instance of the class with the following
statement:
var libraryObject = new window.runtime.utilities.LibraryClass();
Note: To compile an ActionScript SWF library for use as part of an HTML page in AIR, use the acompc compiler. The
acompc utility is part of the Flex 3 SDK and is described in the
lib subdirectory of the root application folder,
“Defining properties in the application
Flex 3 SDK documentation.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Accessing the HTML DOM and JavaScript objects from an imported
ActionScript file
To access objects in an HTML page from ActionScript in a SWF file imported into the page using the <script> tag,
pass a reference to a JavaScript object, such as
Use the reference within the function to access the JavaScript object (or other objects accessible through the passed-in
reference).
For example, consider the following HTML page:
<html>
<script src="ASLibrary.swf" type="application/x-shockwave-flash"></script>
<script>
num = 254;
function getStatus() {
return "OK.";
}
function runASFunction(window){
var obj = new runtime.ASClass();
obj.accessDOM(window);
}
</script>
<body onload="runASFunction">
<p id="p1">Body text.</p>
</body>
</html>
window or document, to a function defined in the ActionScript code.
61
This simple HTML page has a JavaScript variable named num and a JavaScript function named getStatus(). Both of
these are properties of the
window object of the page. Also, the window.document object includes a named P element
(with the ID p1).
The page loads an ActionScript file, “ASLibrary.swf,” that contains a class, ASClass. ASClass defines a function named
accessDOM() that simply traces the values of these JavaScript objects. The accessDOM() method takes the JavaScript
Window object as an argument. Using this Window reference, it can access other objects in the page including
variables, functions, and DOM elements as illustrated in the following definition:
public class ASClass{
public function accessDOM(window:*):void {
trace(window.num); // 254
trace(window.document.getElementById("p1").innerHTML); // Body text..
trace(window.getStatus()); // OK.
}
}
You can both get and set properties of the HTML page from an imported ActionScript class. For example, the
following function sets the contents of the
p1 element on the page and it sets the value of the foo JavaScript variable
on the page:
public function modifyDOM(window:*):void {
window.document.getElementById("p1").innerHTML = "Bye";
window.foo = 66;
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Converting Date and RegExp objects
The JavaScript and ActionScript languages both define Date and RegExp classes, but objects of these types are not
automatically converted between the two execution contexts. You must convert Date and RegExp objects to the
equivalent type before using them to set properties or function parameters in the alternate execution context.
For example, the following ActionScript code converts a JavaScript Date object named jsDate to an ActionScript
Date object:
var asDate:Date = new Date(jsDate.getMilliseconds());
The following ActionScript code converts a JavaScript RegExp object named jsRegExp to an ActionScript RegExp
object:
var flags:String = "";
if (jsRegExp.dotAll) flags += "s";
if (jsRegExp.extended) flags += "x";
if (jsRegExp.global) flags += "g";
if (jsRegExp.ignoreCase) flags += "i";
if (jsRegExp.multiline) flags += "m";
var asRegExp:RegExp = new RegExp(jsRegExp.source, flags);
62
Manipulating an HTML stylesheet from ActionScript
Once the HTMLLoader object has dispatched the complete event, you can examine and manipulate CSS styles in a
page.
For example, consider the following simple HTML document:
After an HTMLLoader object loads this content, you can manipulate the CSS styles in the page via the cssRules array
window.document.styleSheets array, as shown here:
of the
Last updated12/9/2009
var html:HTMLLoader = new HTMLLoader( );
var urlReq:URLRequest = new URLRequest("test.html");
html.load(urlReq);
html.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
var styleSheet0:Object = html.window.document.styleSheets[0];
styleSheet0.cssRules[0].style.fontSize = "32px";
styleSheet0.cssRules[1].style.color = "#FF0000";
var styleSheet1:Object = html.window.document.styleSheets[1];
styleSheet1.cssRules[0].style.color = "blue";
styleSheet1.cssRules[0].style.font-family = "Monaco";
}
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
This code adjusts the CSS styles so that the resulting HTML document appears like the following:
Keep in mind that code can add styles to the page after the HTMLLoader object dispatches the complete event.
63
Cross-scripting content in different security sandboxes
The runtime security model isolates code from different origins. By cross-scripting content in different security
sandboxes, you can allow content in one security sandbox to access selected properties and methods in another
sandbox.
AIR security sandboxes and JavaScript code
AIR enforces a same-origin policy that prevents code in one domain from interacting with content in another. All files
are placed in a sandbox based on their origin. Ordinarily, content in the application sandbox cannot violate the sameorigin principle and cross-script content loaded from outside the application install directory. However, AIR provides
a few techniques that let you cross-script non-application content.
One technique uses frames or iframes to map application content into a different security sandbox. Any pages loaded
from the sandboxed area of the application behave as if they were loaded from the remote domain. For example, by
mapping application content to the example.com domain, that content could cross-script pages loaded from
example.com.
Since this technique places the application content into a different sandbox, code within that content is also no longer
subject to the restrictions on the execution of code in evaluated strings. You can use this sandbox mapping technique
to ease these restrictions even when you don’t need to cross-script remote content. Mapping content in this way can
be especially useful when working with one of the many JavaScript frameworks or with existing code that relies on
evaluating strings. However, you should consider and guard against the additional risk that untrusted content could
be injected and executed when content is run outside the application sandbox.
At the same time, application content mapped to another sandbox loses its access to the AIR APIs, so the sandbox
mapping technique cannot be used to expose AIR functionality to code executed outside the application sandbox.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Another cross-scripting technique lets you create an interface called a sandbox bridge between content in a nonapplication sandbox and its parent document in the application sandbox. The bridge allows the child content to access
properties and methods defined by the parent, the parent to access properties and methods defined by the child, or both.
Finally, you can also perform cross-domain XMLHttpRequests from the application sandbox and, optionally, from
other sandboxes.
For more information, see “HTML frame and iframe elements” on page 77, “HTML security” on page 106, and “The
XMLHttpRequest object” on page 71.
Loading application content into a non-application sandbox
To allow application content to safely cross-script content loaded from outside the application install directory, you
frame or iframe elements to load application content into the same security sandbox as the external content.
can use
If you do not need to cross-script remote content, but still wish to load a page of your application outside the
application sandbox, you can use the same technique, specifying
as the domain of origin.
AIR adds the new attributes, sandboxRoot and documentRoot, to the frame element that allow you to specify whether
an application file loaded into the frame should be mapped to a non-application sandbox. Files resolving to a path
underneath the
sandboxRoot URL are loaded instead from the documentRoot directory. For security purposes, the
application content loaded in this way is treated as if it was actually loaded from the
http://localhost/ or some other innocuous value,
sandboxRoot URL.
64
The sandboxRoot property specifies the URL to use for determining the sandbox and domain in which to place the
frame content. The
file:, http:, or https: URL schemes must be used. If you specify a relative URL, the content
remains in the application sandbox.
The documentRoot property specifies the directory from which to load the frame content. The file:, app:, or app-
storage: URL schemes must be used.
The following example maps content installed in the sandbox subdirectory of the application to run in the remote
sandbox and the
The sandboxRoot URL will mask any content at the same URL on the remote server. In the above example, you would
not be able to access any remote content at
www.example.com/local/ (or any of its subdirectories) because AIR
remaps the request to the local application directory. Requests are remapped whether they derive from page
navigation, from an XMLHttpRequest, or from any other means of loading content.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Setting up a sandbox bridge interface
You can use a sandbox bridge when content in the application sandbox must access properties or methods defined by
content in a non-application sandbox, or when non-application content must access properties and methods defined
by content in the application sandbox. Create a bridge with the
properties of the
window object of any child document.
childSandboxBridge and parentSandboxBridge
Establishing a child sandbox bridge
The childSandboxBridge property allows the child document to expose an interface to content in the parent
document. To expose an interface, you set the
You can then access the object or function from content in the parent document. The following example shows how a
script running in a child document can expose an object containing a function and a property to its parent:
The parentSandboxBridge property allows the parent document to expose an interface to content in a child
document. To expose an interface, the parent document sets the
function or object defined in the parent document. You can then access the object or function from content in the
child. The following example shows how a script running in a parent frame can expose an object containing a function
to a child document:
var interface = {};
interface.save = function(text){
var saveFile = air.File("app-storage:/save.txt");
//write text to file
}
document.getElementById("child").contentWindow.parentSandboxBridge = interface;
Using this interface, content in the child frame could save text to a file named save.txt, but would not have any other
access to the file system. The child content could call the save function as follows:
var textToSave = "A string.";
window.parentSandboxBridge.save(textToSave);
Application content should expose the narrowest interface possible to other sandboxes. Non-application content
should be considered inherently untrustworthy since it may be subject to accidental or malicious code injection. You
must put appropriate safeguards in place to prevent misuse of the interface you expose through the parent sandbox
bridge.
parentSandbox property of the child document to a
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Programming in HTML and JavaScript
Accessing a parent sandbox bridge during page loading
In order for a script in a child document to access a parent sandbox bridge, the bridge must be set up before the script
is run. Window, frame and iframe objects dispatch a
but before any scripts have been parsed, or DOM elements added. You can use the
the bridge early enough in the page construction sequence that all scripts in the child document can access it.
The following example illustrates how to create a parent sandbox bridge in response to the dominitialize event
dispatched from the child frame:
To listen for the dominitialize event on a child window, rather than a frame, you must add the listener to the new
child window object created by the
var childWindow = window.open();
childWindow.addEventListener("dominitialize", engageBridge());
childWindow.document.location = "http://www.example.com/air/child.html";
window.open() function:
In this case, there is no way to map application content into a non-application sandbox. This technique is only useful
child.html is loaded from outside the application directory. You can still map application content in the
when
window to a non-application sandbox, but you must first load an intermediate page that itself uses frames to load the
child document and map it to the desired sandbox.
If you use the HTMLLoader class createRootWindow() function to create a window, the new window is not a child
of the document from which
createRootWindow() is called. Thus, you cannot create a sandbox bridge from the
calling window to non-application content loaded into the new window. Instead, you must use load an intermediate
page in the new window that itself uses frames to load the child document. You can then establish the bridge from the
parent document of the new window to the child document loaded into the frame.
Last updated12/9/2009
Chapter 11: About the HTML
environment
AIR uses WebKit (www.webkit.org), also used by the Safari web browser, to parse, layout, and render HTML and
JavaScript content. The built-in host classes and objects of AIR provide an API for features traditionally associated
with desktop applications. Such features include reading and writing files and managing windows. Adobe AIR also
inherits APIs from the Adobe® Flash® Player, which include features like sound and binary sockets.
Important: New versions of the Adobe AIR runtime may include updated versions of WebKit. A WebKit update in a
new version of AIR may result in unexpected changes in a deployed AIR application. These changes may affect the
behavior or appearance of HTML content in an application. For example, improvements or corrections in WebKit
rendering may change the layout of elements in an application’s user interface. For this reason, it is highly
recommended that you provide an update mechanism in your application. Should you need to update your application
due to a change in the WebKit version included in AIR, the AIR update mechanism can prompt the user to install the
new version of your application. For more information, see
Using the AIR APIs in HTML content is entirely optional. You can program an AIR application entirely with HTML
and JavaScript. Most existing HTML applications should run with few changes (assuming they use HTML, CSS, DOM,
and JavaScript features compatible with WebKit).
“Updating AIR applications” on page 376.
67
AIR gives you complete control over the look-and-feel of your application. You can make your application look like a
native desktop application. You can turn off the window chrome provided by the operating system and implement
your own controls for moving, resizing, and closing windows. You can even run without a window.
Because AIR applications run directly on the desktop, with full access to the file system, the security model is more
stringent than the security model of the typical web browser. In AIR, only content loaded from the application
installation directory is placed in the application sandbox. The application sandbox has the highest level of privilege
and allows access to the AIR APIs. AIR places other content into isolated sandboxes based on where that content came
from. Files loaded from the file system go into a local sandbox. Files loaded from the network using the http: or https:
protocols go into a sandbox based on the domain of the remote server. Content in these non-application sandboxes is
prohibited from accessing any AIR API and runs much as it would in a typical web browser.
HTML content in AIR does not display SWF or PDF content if alpha, scaling, or transparency settings are applied. For
more information, see
transparency” on page 136.
Considerations when loading SWF or PDF content in an HTML pageand “Window
Overview of the HTML environment
Adobe AIR provides a complete browser-like JavaScript environment with an HTML renderer, document object
model, and JavaScript interpreter. The JavaScript environment is represented by the AIR HTMLLoader class. In
HTML windows, an HTMLLoader object contains all HTML content, and is, in turn, contained within a
NativeWindow object. The NativeWindow object allows an application to script the properties and behavior of native
operating system window displayed on the user’s desktop.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
About the JavaScript environment and its relationship to AIR
The following diagram illustrates the relationship between the JavaScript environment and the AIR run-time
environment. Although only a single native window is shown, an AIR application can contain multiple windows. (And
a single window can contain multiple HTMLLoader objects.)
AIR Run-time Environment
NativeWindow
HTMLLoader
window
JavaScript
Environment
window
68
window
body
h1divptable
The JavaScript environment has its own Document and Window objects. JavaScript code can interact with the AIR run-time environment
through the runtime, nativeWindow, and htmlLoader properties. ActionScript code can interact with the JavaScript environment through the
window property of an HTMLLoader object, which is a reference to the JavaScript Window object. In addition, both ActionScript and JavaScript
objects can listen for events dispatched by both AIR and JavaScript objects.
head
htmlLoader
native4Window
runtime
The runtime property provides access to AIR API classes, allowing you to create new AIR objects as well as access class
(also called static) members. To access an AIR API, you add the name of the class, with package, to the
runtime
property. For example, to create a File object, you would use the statement:
var file = new window.runtime.filesystem.File();
Note: The AIR SDK provides a JavaScript file, AIRAliases.js, that defines more convenient aliases for the most
commonly used AIR classes. When you import this file, you can use the shorter form air.Class instead of
window.runtime.package.Class. For example, you could create the File object with
new air.File().
The NativeWindow object provides properties for controlling the desktop window. From within an HTML page, you
can access the containing NativeWindow object with the
window.nativeWindow property.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
The HTMLLoader object provides properties, methods, and events for controlling how content is loaded and
rendered. From within an HTML page, you can access the parent HTMLLoader object with the
window.htmlLoader
property.
Important: Only pages installed as part of an application have the htmlLoader, nativeWindow, or runtime properties
and only when loaded as the top-level document. These properties are not added when a document is loaded into a frame
or iframe. (A child document can access these properties on the parent document as long as it is in the same security
sandbox. For example, a document loaded in a frame could access the
parent.runtime.)
runtime property of its parent with
About security
AIR executes all code within a security sandbox based on the domain of origin. Application content, which is limited
to content loaded from the application installation directory, is placed into the application sandbox. Access to the runtime environment and the AIR APIs are only available to HTML and JavaScript running within this sandbox. At the
same time, most dynamic evaluation and execution of JavaScript is blocked in the application sandbox after all
handlers for the page
You can map an application page into a non-application sandbox by loading the page into a frame or iframe and setting
the AIR-specific
actual remote domain, you can enable the sandboxed content to cross-script content in that domain. Mapping pages
in this way can be useful when loading and scripting remote content, such as in a mash-up application.
load event have returned.
sandboxRoot and documentRoot attributes of the frame. By setting the sandboxRoot value to an
69
Another way to allow application and non-application content to cross-script each other, and the only way to give nonapplication content access to AIR APIs, is to create a sandbox bridge. A parent-to-child bridge allows content in a child
frame, iframe, or window to access designated methods and properties defined in the application sandbox. Conversely,
a child-to-parent bridge allows application content to access designated methods and properties defined in the sandbox
of the child. Sandbox bridges are established by setting the
properties of the window object. For more information, see
parentSandboxBridge and childSandboxBridge
“HTML security” on page 106 and “HTML frame and
iframe elements” on page 77.
About plug-ins and embedded objects
AIR supports the Adobe® Acrobat® plug-in. Users must have Acrobat or Adobe® Reader® 8.1 (or better) to display PDF
content. The HTMLLoader object provides a property for checking whether a user’s system can display PDF. SWF file
content can also be displayed within the HTML environment, but this capability is built in to AIR and does not use an
external plug-in.
No other WebKit plug-ins are supported in AIR.
More Help topics
“HTML security” on page 106
“HTML Sandboxes” on page 70
“HTML frame and iframe elements” on page 77
“JavaScript Window object” on page 75
“The XMLHttpRequest object” on page 71
“Adding PDF content” on page 293
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
AIR and WebKit extensions
Adobe AIR uses the open source WebKit engine, also used in the Safari web browser. AIR adds several extensions to
allow access to the runtime classes and objects as well as for security. In addition, WebKit itself adds features not
included in the W3C standards for HTML, CSS, and JavaScript.
Only the AIR additions and the most noteworthy WebKit extensions are covered here; for additional documentation
on non-standard HTML, CSS, and JavaScript, see
information, see the W3C website. Mozilla also provides a valuable general reference on HTML, CSS, and DOM topics
(of course, the WebKit and Mozilla engines are not identical).
Note: AIR does not support the following standard and extended WebKit features: the JavaScript Window object
print() method; plug-ins, except Acrobat or Adobe Reader 8.1+; Scalable Vector Graphics (SVG), the CSS opacity
property.
JavaScript in AIR
AIR makes several changes to the typical behavior of common JavaScript objects. Many of these changes are made to
make it easier to write secure applications in AIR. At the same time, these differences in behavior mean that some
common JavaScript coding patterns, and existing web applications using those patterns, might not always execute as
expected in AIR. For information on correcting these types of issues, see
on page 53.
www.webkit.org and developer.apple.com. For standards
“Avoiding security-related JavaScript errors”
70
HTML Sandboxes
AIR places content into isolated sandboxes according to the origin of the content. The sandbox rules are consistent
with the same-origin policy implemented by most web browsers, as well as the rules for sandboxes implemented by
the Adobe Flash Player. In addition, AIR provides a new application sandbox type to contain and protect application
content. See
developing AIR applications.
Access to the run-time environment and AIR APIs are only available to HTML and JavaScript running within the
application sandbox. At the same time, however, dynamic evaluation and execution of JavaScript, in its various forms,
is largely restricted within the application sandbox for security reasons. These restrictions are in place whether or not
your application actually loads information directly from a server. (Even file content, pasted strings, and direct user
input may be untrustworthy.)
The origin of the content in a page determines the sandbox to which it is consigned. Only content loaded from the
application directory (the installation directory referenced by the
sandbox. Content loaded from the file system is placed in the local-with-filesystem or the local-trusted sandbox, which
allows access and interaction with content on the local file system, but not remote content. Content loaded from the
network is placed in a remote sandbox corresponding to its domain of origin.
To allow an application page to interact freely with content in a remote sandbox, the page can be mapped to the same
domain as the remote content. For example, if you write an application that displays map data from an Internet service,
the page of your application that loads and displays content from the service could be mapped to the service domain.
The attributes for mapping pages into a remote sandbox and domain are new attributes added to the frame and iframe
HTML elements.
“Sandboxes” on page 104 for more information on the types of sandboxes you may encounter when
app: URL scheme) is placed in the application
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
To allow content in a non-application sandbox to safely use AIR features, you can set up a parent sandbox bridge. To
allow application content to safely call methods and access properties of content in other sandboxes, you can set up a
child sandbox bridge. Safety here means that remote content cannot accidentally get references to objects, properties,
or methods that are not explicitly exposed. Only simple data types, functions, and anonymous objects can be passed
across the bridge. However, you must still avoid explicitly exposing potentially dangerous functions. If, for example,
you exposed an interface that allowed remote content to read and write files anywhere on a user’s system, then you
might be giving remote content the means to do considerable harm to your users.
JavaScript eval() function
Use of the eval() function is restricted within the application sandbox once a page has finished loading. Some uses
are permitted so that JSON-formatted data can be safely parsed, but any evaluation that results in executable
statements results in an error.
“Code restrictions for content in different sandboxes” on page 108 describes the allowed
uses of the eval() function.
Function constructors
In the application sandbox, function constructors can be used before a page has finished loading. After all page load
event handlers have finished, new functions cannot be created.
Loading external scripts
HTML pages in the application sandbox cannot use the script tag to load JavaScript files from outside of the
application directory. For a page in your application to load a script from outside the application directory, the page
must be mapped to a non-application sandbox.
71
The XMLHttpRequest object
AIR provides an XMLHttpRequest (XHR) object that applications can use to make data requests. The following
example illustrates a simple data request:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http:/www.example.com/file.data", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
//do something with data...
}
}
xmlhttp.send(null);
In contrast to a browser, AIR allows content running in the application sandbox to request data from any domain. The
result of an XHR that contains a JSON string can be evaluated into data objects unless the result also contains
executable code. If executable statements are present in the XHR result, an error is thrown and the evaluation attempt
fails.
To prevent accidental injection of code from remote sources, synchronous XHRs return an empty result if made before
a page has finished loading. Asynchronous XHRs will always return after a page has loaded.
By default, AIR blocks cross-domain XMLHttpRequests in non-application sandboxes. A parent window in the
application sandbox can choose to allow cross-domain requests in a child frame containing content in a nonapplication sandbox by setting
iframe element:
allowCrossDomainXHR, an attribute added by AIR, to true in the containing frame or
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
Note: When convenient, the AIR URLStream class can also be used to download data.
If you dispatch an XMLHttpRequest to a remote server from a frame or iframe containing application content that has
been mapped to a remote sandbox, make sure that the mapping URL does not mask the server address used in the
XHR. For example, consider the following iframe definition, which maps application content into a remote sandbox
for the example.com domain:
Because the sandboxRoot attribute remaps the root URL of the www.example.com address, all requests are loaded
from the application directory and not the remote server. Requests are remapped whether they derive from page
navigation or from an XMLHttpRequest.
To avoid accidentally blocking data requests to your remote server, map the sandboxRoot to a subdirectory of the
remote URL rather than the root. The directory does not have to exist. For example, to allow requests to the
www.example.com to load from the remote server rather than the application directory, change the previous iframe to
the following:
In this case, only content in the air subdirectory is loaded locally.
For more information on sandbox mapping see “HTML frame and iframe elements” on page 77 and “HTML security”
on page 106.
The Canvas object
The Canvas object defines an API for drawing geometric shapes such as lines, arcs, ellipses, and polygons. To use the
canvas API, you first add a canvas element to the document and then draw into it using the JavaScript Canvas API. In
most other respects, the Canvas object behaves like an image.
The following example draws a triangle using a Canvas object:
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
For more documentation on the Canvas API, see the Safari JavaScript Reference from Apple. Note that the WebKit
project recently began changing the Canvas API to standardize on the HTML 5 Working Draft proposed by the Web
Hypertext Application Technology Working Group (WHATWG) and W3C. As a result, some of the documentation
in the Safari JavaScript Reference may be inconsistent with the version of the canvas present in AIR.
73
Cookies
In AIR applications, only content in remote sandboxes (content loaded from http: and https: sources) can use cookies
document.cookie property). In the application sandbox, AIR APIs provide other means for storing persistent
(the
data (such as the EncryptedLocalStore and FileStream classes).
The Clipboard object
The WebKit Clipboard API is driven with the following events: copy, cut, and paste. The event object passed in these
events provides access to the clipboard through the
clipboardData object to read or write clipboard data:
MethodDescription
clearData(mimeType)Clears the clipboard data. Set the mimeType parameter to the MIME type of the data to clear.
getData(mimeType)Get the clipboard data. This method can only be called in a handler for the paste event. Set the mimeType
parameter to the MIME type of the data to return.
setData(mimeType, data)Copy data to the clipboard. Set the mimeType parameter to the MIME type of the data.
JavaScript code outside the application sandbox can only access the clipboard through theses events. However, content
in the application sandbox can access the system clipboard directly using the AIR Clipboard class. For example, you
could use the following statement to get text format data on the clipboard:
var clipping = air.Clipboard.generalClipboard.getData("text/plain",
air.ClipboardTransferMode.ORIGINAL_ONLY);
The valid data MIME types are:
clipboardData property. Use the following methods of the
Last updated12/9/2009
MIME typeValue
Text"text/plain"
HTML"text/html"
URL"text/uri-list"
Bitmap"image/x-vnd.adobe.air.bitmap"
File list"application/x-vnd.adobe.air.file-list"
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
Important: Only content in the application sandbox can access file data present on the clipboard. If non-application
content attempts to access a file object from the clipboard, a security error is thrown.
For more information on using the clipboard, see “Copy and paste” on page 222 and Using the Pasteboard from
JavaScript (Apple Developer Center).
Drag and Drop
Drag-and-drop gestures into and out of HTML produce the following DOM events: dragstart, drag, dragend,
dragenter, dragover, dragleave, and drop. The event object passed in these events provides access to the dragged
data through the
methods as the
function to get text format data from a
dataTransfer property. The dataTransfer property references an object that provides the same
clipboardData object associated with a clipboard event. For example, you could use the following
drop event:
74
function onDrop(dragEvent){
return dragEvent.dataTransfer.getData("text/plain",
air.ClipboardTransferMode.ORIGINAL_ONLY);
}
The dataTransfer object has the following important members:
MemberDescription
clearData(mimeType)Clears the data. Set the mimeType parameter to the MIME type of the data representation to clear.
getData(mimeType) Get the dragged data. This method can only be called in a handler for the drop event. Set the mimeType
setData(mimeType, data) Set the data to be dragged. Set the mimeType parameter to the MIME type of the data.
typesAn array of strings containing the MIME types of all data representations currently available in the
effectsAllowedSpecifies whether the data being dragged can be copied, moved, linked, or some combination thereof. Set the
dropEffectSpecifies which of the allowed drop effects are supported by a drag target. Set the dropEffect property in
parameter to the MIME type of the data to get.
dataTransfer object.
effectsAllowed property in the handler for the dragstart event.
the handler for the
occur if the user released the mouse. If no
chosen. The copy effect has priority over the move effect, which itself has priority over the link effect. The user
can modify the default priority using the keyboard.
dragEnter event. During the drag, the cursor changes to indicate which effect would
dropEffect is specified, an effectsAllowed property effect is
For more information on adding support for drag-and-drop to an AIR application see “Drag and drop” on page 213
and Using the Drag-and-Drop from JavaScript (Apple Developer Center).
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
innerHTML and outerHTML properties
AIR places security restrictions on the use of the innerHTML and outerHTML properties for content running in the
application sandbox. Before the page load event, as well as during the execution of any load event handlers, use of the
innerHTML and outerHTML properties is unrestricted. However, once the page has loaded, you can only use
innerHTML or outerHTML properties to add static content to the document. Any statement in the string assigned to
innerHTML or outerHTML that evaluates to executable code is ignored. For example, if you include an event callback
attribute in an element definition, the event listener is not added. Likewise, embedded
evaluated. For more information, see the
“HTML security” on page 106.
<script> tags are not
Document.write() and Document.writeln() methods
Use of the write() and writeln() methods is not restricted in the application sandbox before the load event of the
page. However, once the page has loaded, calling either of these methods does not clear the page or create a new one.
In a non-application sandbox, as in most web browsers, calling
document.write() or writeln() after a page has
finished loading clears the current page and opens a new, blank one.
Document.designMode property
Set the document.designMode property to a value of on to make all elements in the document editable. Built-in editor
support includes text editing, copy, paste, and drag-and-drop. Setting
contentEditable property of the body element to true. You can use the contentEditable property on most
HTML elements to define which sections of a document are editable. See
page 80 for additional information.
designMode to on is equivalent to setting the
“HTML contentEditable attribute” on
75
unload events (for body and frameset objects)
In the top-level frameset or body tag of a window (including the main window of the application), do not use the
unload event to respond to the window (or application) being closed. Instead, use exiting event of the
NativeApplication object (to detect when an application is closing). Or use the
closing event of the NativeWindow
object (to detect when a window is closing). For example, the following JavaScript code displays a message
"Goodbye.") when the user closes the application:
(
var app = air.NativeApplication.nativeApplication;
app.addEventListener(air.Event.EXITING, closeHandler);
function closeHandler(event)
{
alert("Goodbye.");
}
However, scripts can successfully respond to the unload event caused by navigation of a frame, iframe, or top-level
window content.
Note: These limitations may be removed in a future version of Adobe AIR.
JavaScript Window object
The Window object remains the global object in the JavaScript execution context. In the application sandbox, AIR
adds new properties to the JavaScript Window object to provide access to the built-in classes of AIR, as well as
important host objects. In addition, some methods and properties behave differently depending on whether they are
within the application sandbox or not.
Window.runtime property The runtime property allows you to instantiate and use the built-in runtime classes from
within the application sandbox. These classes include the AIR and Flash Player APIs (but not, for example, the Flex
framework). For example, the following statement creates an AIR file object:
var preferencesFile = new window.runtime.flash.filesystem.File();
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
The AIRAliases.js file, provided in the AIR SDK, contains alias definitions that allow you to shorten such references.
For example, when
var preferencesFile = new air.File();
AIRAliases.js is imported into a page, a File object can be created with the following statement:
The window.runtime property is only defined for content within the application sandbox and only for the parent
document of a page with frames or iframes.
See “Using the AIRAliases.js file” on page 58.
Window.nativeWindow property The nativeWindow property provides a reference to the underlying native window
object. With this property, you can script window functions and properties such as screen position, size, and visibility,
and handle window events such as closing, resizing, and moving. For example, the following statement closes the
window:
window.nativeWindow.close();
Note: The window control features provided by the NativeWindow object overlap the features provided by the JavaScript
Window object. In such cases, you can use whichever method you find most convenient.
The window.nativeWindow property is only defined for content within the application sandbox and only for the
parent document of a page with frames or iframes.
Window.htmlLoader property The htmlLoader property provides a reference to the AIR HTMLLoader object that
contains the HTML content. With this property, you can script the appearance and behavior of the HTML
environment. For example, you can use the
htmlLoader.paintsDefaultBackground property to determine whether
Note: The HTMLLoader object itself has a window property, which references the JavaScript Window object of the HTML
content it contains. You can use this property to access the JavaScript environment through a reference to the containing
HTMLLoader.
The window.htmlLoader property is only defined for content within the application sandbox and only for the parent
document of a page with frames or iframes.
Window.parentSandboxBridge and Window.childSandboxBridge properties The parentSandboxBridge and
childSandboxBridge properties allow you to define an interface between a parent and a child frame. For more
information, see
Window.setTimeout() and Window.setInterval() functions AIR places security restrictions on use of the
setTimeout() and setInterval() functions within the application sandbox. You cannot define the code to be
executed as a string when calling
information, see
Window.open() function When called by code running in a non-application sandbox, the open() method only opens
“Cross-scripting content in different security sandboxes” on page 63.
setTimeout() or setInterval(). You must use a function reference. For more
“setTimeout() and setInterval()” on page 56.
a window when called as a result of user interaction (such as a mouse click or keypress). In addition, the window title
is prefixed with the application title (to prevent windows opened by remote content from impersonating windows
opened by the application). For more information, see the
“Restrictions on calling the JavaScript window.open()
method” on page 111.
air.NativeApplication object
The NativeApplication object provides information about the application state, dispatches several important
application-level events, and provides useful functions for controlling application behavior. A single instance of the
NativeApplication object is created automatically and can be accessed through the class-defined
NativeApplication.nativeApplication property.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
To access the object from JavaScript code you could use:
var app = window.runtime.flash.desktop.NativeApplication.nativeApplication;
Or, if the AIRAliases.js script has been imported, you could use the shorter form:
var app = air.NativeApplication.nativeApplication;
The NativeApplication object can only be accessed from within the application sandbox. Interacting with the
operating system
“Working with runtime and operating system information” on page 337 describes the
NativeApplication object in detail.
The JavaScript URL scheme
Execution of code defined in a JavaScript URL scheme (as in href="javascript:alert('Test')") is blocked within
the application sandbox. No error is thrown.
Extensions to HTML
AIR and WebKit define a few non-standard HTML elements and attributes, including:
“HTML frame and iframe elements” on page 77
“HTML Canvas element” on page 79
77
“HTML element event handlers” on page 79
HTML frame and iframe elements
AIR adds new attributes to the frame and iframe elements of content in the application sandbox:
sandboxRoot attribute The sandboxRoot attribute specifies an alternate, non-application domain of origin for the file
specified by the frame
domain. Content in the file and content loaded from the specified domain can cross-script each other.
Important: If you set the value of sandboxRoot to the base URL of the domain, all requests for content from that domain
are loaded from the application directory instead of the remote server (whether that request results from page navigation,
from an XMLHttpRequest, or from any other means of loading content).
documentRoot attribute The documentRoot attribute specifies the local directory from which to load URLs that
resolve to files within the location specified by
When resolving URLs, either in the frame src attribute, or in content loaded into the frame, the part of the URL
matching the value specified in
following frame tag:
child.html is loaded from the sandbox subdirectory of the application installation folder. Relative URLs in
child.html are resolved based on sandbox directory. Note that any files on the remote server at
www.example.com/air are not accessible in the frame, since AIR would attempt to load them from the app:/sandbox/
directory.
src attribute. The file is loaded into the non-application sandbox corresponding to the specified
sandboxRoot.
sandboxRoot is replaced with the value specified in documentRoot. Thus, in the
allowCrossDomainXHR attribute Include allowCrossDomainXHR="allowCrossDomainXHR" in the opening frame
tag to allow content in the frame to make XMLHttpRequests to any remote domain. By default, non-application
content can only make such requests to its own domain of origin. There are serious security implications involved in
allowing cross-domain XHRs. Code in the page is able to exchange data with any domain. If malicious content is
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
About the HTML environment
somehow injected into the page, any data accessible to code in the current sandbox can be compromised. Only enable
cross-domain XHRs for pages that you create and control and only when cross-domain data loading is truly necessary.
Also, carefully validate all external data loaded by the page to prevent code injection or other forms of attack.
Important: If the allowCrossDomainXHR attribute is included in a frame or iframe element, cross-domain XHRs are
enabled (unless the value assigned is "0" or starts with the letters "f" or "n"). For example, setting
deny" would still enable cross-domain XHRs. Leave the attribute out of the element declaration altogether if you do
to "
allowCrossDomainXHR
not want to enable cross-domain requests.
ondominitialize attribute Specifies an event handler for the dominitialize event of a frame. This event is an AIR-
specific event that fires when the window and document objects of the frame have been created, but before any scripts
have been parsed or document elements created.
The frame dispatches the dominitialize event early enough in the loading sequence that any script in the child page
can reference objects, variables, and functions added to the child document by the
dominitialize handler. The
parent page must be in the same sandbox as the child to directly add or access any objects in a child document.
However, a parent in the application sandbox can establish a sandbox bridge to communicate with content in a nonapplication sandbox.
The following examples illustrate use of the iframe tag in AIR:
Place child.html in a remote sandbox, without mapping to an actual domain on a remote server:
For more information, see “Cross-scripting content in different security sandboxes” on page 63 and “HTML security”
on page 106.
HTML Canvas element
Defines a drawing area for use with the WebKit Canvas API. Graphics commands cannot be specified in the tag itself.
To draw into the canvas, call the canvas drawing methods through JavaScript.
For more informtion, see “The Canvas object” on page 72.
HTML element event handlers
DOM objects in AIR and WebKit dispatch some events not found in the standard DOM event model. The following
table lists the related event attributes you can use to specify handlers for these events:
Callback attribute nameDescription
oncontextmenu Called when a context menu is invoked, such as through a right-click
oncopyCalled when a selection in an element is copied.
oncut Called when a selection in an element is cut.
ondominitializeCalled when the DOM of a document loaded in a frame or iframe is
ondrag Called when an element is dragged.
or command-click on selected text.
created, but before any DOM elements are created or scripts parsed.
Last updated12/9/2009
Callback attribute nameDescription
ondragend Called when a drag is released.
ondragenter Called when a drag gesture enters the bounds of an element.
ondragleave Called when a drag gesture leaves the bounds of an element.
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
80
About the HTML environment
ondragover Called continuously while a drag gesture is within the bounds of an
ondragstart Called when a drag gesture begins.
ondrop Called when a drag gesture is released while over an element.
onerror Called when an error occurs while loading an element.
oninput Called when text is entered into a form element.
onpaste Called when an item is pasted into an element.
onscroll Called when the content of a scrollable element is scrolled.
onsearch Called when an element is copied (? Apple docs correct ?)
onselectstart Called when a selection begins.
element.
HTML contentEditable attribute
You can add the contentEditable attribute to any HTML element to allow users to edit the content of the element.
For example, the following example HTML code sets the entire document as editable, except for first
<html>
<head/>
<body contentEditable="true">
<h1>de Finibus Bonorum et Malorum</h1>
<p contentEditable="false">Sed ut perspiciatis unde omnis iste natus error.</p>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis.</p>
</body>
</html>
p element:
Note: If you set the document.designMode property to on, then all elements in the document are editable, regardless of
the setting of
editing of elements for which
contentEditable for an individual element. However, setting designMode to off, does not disable
contentEditable is true. See “Document.designMode property” on page 75 for
additional information.
Extensions to CSS
WebKit supports several extended CSS properties. The following table lists the extended properties for which support
is established. Additional non-standard properties are available in WebKit, but are not fully supported in AIR, either
because they are still under development in WebKit, or because they are experimental features that may be removed
in the future.
Last updated12/9/2009
CSS property nameValuesDescription
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
81
About the HTML environment
-webkit-border-horizontal-spacingNon-negative unit of lengthSpecifies the horizontal component of the
-webkit-border-vertical-spacingNon-negative unit of lengthSpecifies the vertical component of the
-webkit-line-breakafter-white-space, normalSpecifies the line break rule to use for
-webkit-margin-bottom-collapsecollapse, discard, separateDefines how the bottom margin of a table
-webkit-margin-collapsecollapse, discard, separateDefines how the top and bottom margins
-webkit-margin-startAny unit of length.The width of the starting margin. For left-
-webkit-margin-top-collapsecollapse, discard, separateDefines how the top margin of a table cell
-webkit-nbsp-modenormal, spaceDefines the behavior of non-breaking
-webkit-padding-startAny unit of lengthSpecifies the width of the starting
border spacing.
border spacing.
Chinese, Japanese, and Korean (CJK) text.
cell collapses.
of a table cell collapses.
to-right text, this property overrides the
left margin. For right-to-left text, this
property overrides the right margin.
collapses.
spaces within the enclosed content.
padding. For left-to-right text, this
property overrides the left padding value.
For right-to-left text, this property
overrides the right padding value.
-webkit-rtl-orderinglogical, visualOverrides the default handling of mixed
-webkit-text-fill-colorAny named color or numeric color valueSpecifies the text fill color.
-webkit-text-securitycircle, disc, none, squareSpecifies the replacement shape to use in
An event-handling system allows programmers to respond to user input and system events in a convenient way. The
Adobe® AIR® event model is not only convenient, but also standards-compliant. Based on the Document Object Model
(DOM) Level 3 Events Specification, an industry-standard event-handling architecture, the event model provides a
powerful, yet intuitive, event-handling tool for programmers.
HTMLLoader events
An HTMLLoader object dispatches the following Adobe® ActionScript® 3.0 events:
EventDescription
82
htmlDOMInitializeDispatched when the HTML document is created, but before any scripts are parsed or
completeDispatched when the HTML DOM has been created in response to a load operation,
htmlBoundsChangedDispatched when one or both of the contentWidth and contentHeight
locationChangeDispatched when the location property of the HTMLLoader has changed.
scrollDispatched anytime the HTML engine changes the scroll position. Scroll events can be
uncaughtScriptExceptionDispatched when a JavaScript exception occurs in the HTMLLoader and the exception
You can also register an ActionScript function for a JavaScript event (such as onClick). For details, see Handling
DOM events with ActionScript.
DOM nodes are added to the page.
immediately after the
properties have changed.
because of navigation to anchor links (
window.scrollTo() method. Entering text in a text input or text area can also
cause a scroll event.
is not caught in JavaScript code.
onload event in the HTML page.
# links) in the page or because of calls to the
How AIR class-event handling differs from other event
handling in the HTML DOM
The HTML DOM provides a few different ways to handle events:
• Defining an on event handler within an HTML element opening tag, as in:
<div id="myDiv" onclick="myHandler()">
• Callback function properties, such as:
document.getElementById("myDiv").onclick
• Event listeners that you register using the addEventListener() method, as in:
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Handling HTML-related events
However, since runtime objects do not appear in the DOM, you can only add event listeners by calling the
addEventListener() method of an AIR object.
As in JavaScript, events dispatched by AIR objects can be associated with default behaviors. (A default behavior is an
action that AIR executes as the normal consequence of certain events.)
The event objects dispatched by runtime objects are an instance of the Event class or one of its subclasses. An event
object not only stores information about a specific event, but also contains methods that facilitate manipulation of the
event object. For example, when AIR detects an I/O error event when reading a file asynchronously, it creates an event
object (an instance of the IOErrorEvent class) to represent that particular I/O error event.
Any time you write event handler code, it follows the same basic structure:
function eventResponse(eventObject)
{
// Actions performed in response to the event go here.
}
This code does two things. First, it defines a handler function, which is the way to specify the actions to be performed
in response to the event. Next, it calls the
addEventListener() method of the source object, in essence subscribing
the function to the specified event so that when the event happens, the handler actions are carried out. When the event
actually happens, the event target checks its list of all the functions and methods that are registered with event listeners.
It then calls each one in turn, passing the event object as a parameter.
83
Default behaviors
Developers are usually responsible for writing code that responds to events. In some cases, however, a behavior is so
commonly associated with an event that AIR automatically executes the behavior unless the developer adds code to
cancel it. Because AIR automatically exhibits the behavior, such behaviors are called default behaviors.
For example, when a user clicks the close box of a window of an application, the expectation that the window will close
is so common that the behavior is built into AIR. If you do not want this default behavior to occur, you can cancel it
using the event-handling system. When a user clicks the close box of a window, the NativeWindow object that
represents the window dispatches a
preventDefault() method of the dispatched event object.
the
Not all default behaviors can be prevented. For example, the runtime generates an OutputProgressEvent object as a
FileStream object writes data to a file. The default behavior, which cannot be prevented, is that the content of the file
is updated with the new data.
Many types of event objects do not have associated default behaviors. For example, a Sound object dispatches an id3
event when enough data from an MP3 file is read to provide ID3 information, but there is no default behavior
associated with it. The API documentation for the Event class and its subclasses lists each type of event and describes
any associated default behavior, and whether that behavior can be prevented.
Note: Default behaviors are associated only with event objects dispatched by the runtime directly, and do not exist for
event objects dispatched programmatically through JavaScript. For example, you can use the methods of the
EventDispatcher class to dispatch an event object, but dispatching the event does not trigger the default behavior.
closing event. To prevent the runtime from closing the window, you must call
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Handling HTML-related events
The event flow
SWF file content running in AIR uses the ActionScript 3.0 display list architecture to display visual content. The
ActionScript 3.0 display list provides a parent-child relationship for content, and events (such as mouse-click events)
in SWF file content that propagates between parent and child display objects. The HTML DOM has its own, separate
event flow that traverses only the DOM elements. When writing HTML-based applications for AIR, you primarily use
the HTML DOM instead of the ActionScript 3.0 display list, so you can generally disregard the information on event
phases that appears in the runtime language reference.
Adobe AIR event objects
Event objects serve two main purposes in the event-handling system. First, event objects represent actual events by
storing information about specific events in a set of properties. Second, event objects contain a set of methods that
allow you to manipulate event objects and affect the behavior of the event-handling system.
The AIR API defines an Event class that serves as the base class for all event objects dispatched by the AIR API classes.
The Event class defines a fundamental set of properties and methods that are common to all event objects.
To use Event objects, it’s important to first understand the Event class properties and methods and why subclasses of
the Event class exist.
84
Understanding Event class properties
The Event class defines several read-only properties and constants that provide important information about an event.
The following are especially important:
• Event.type describes the type of event that an event object represents.
• Event.cancelable is a Boolean value that reports whether the default behavior associated with the event, if any,
can be canceled.
• Event flow information is contained in the remaining properties, and is only of interest when using ActionScript
3.0 in SWF content in AIR.
Event object types
Every event object has an associated event type. Event types are stored in the Event.type property as string values. It
is useful to know the type of an event object so that your code can distinguish objects of different types from one
another. For example, the following code registers a
event dispatched by
The AIR Event class defines many class constants, such as COMPLETE, CLOSING, and ID3, to represent the types of
events dispatched by runtime objects. These constants are listed in the Event class page of the Adobe AIR Language Reference for HTML Developers.
Event constants provide an easy way to refer to specific event types. Using a constant instead of the string value helps
you identify typographical errors more quickly. If you misspell a constant name in your code, the JavaScript parser will
catch the mistake. If you instead misspell an event string, the event handler will be registered for a type of event that
will never be dispatched. Thus, when adding an event listener, it is a better practice to use the following code:
myFileStream:
fileReadHandler() listener function to respond to a complete
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Handling HTML-related events
Default behavior information
Your code can check whether the default behavior for any given event object can be prevented by accessing the
cancelable property. The cancelable property holds a Boolean value that indicates whether a default behavior can
be prevented. You can prevent, or cancel, the default behavior associated with a small number of events using the
preventDefault() method. For more information, see “Canceling default event behavior” on page 85.
Understanding Event class methods
There are three categories of Event class methods:
• Utility methods, which can create copies of an event object or convert it to a string.
• Event flow methods, which remove event objects from the event flow (primarily of use when using ActionScript 3.0
in SWF content for the runtime—see
• Default behavior methods, which prevent default behavior or check whether it has been prevented.
Event class utility methods
The Event class has two utility methods. The clone() method allows you to create copies of an event object. The
toString() method allows you to generate a string representation of the properties of an event object along with their
values.
“The event flow” on page 84).
85
Canceling default event behavior
The two methods that pertain to canceling default behavior are the preventDefault() method and the
isDefaultPrevented() method. Call the preventDefault() method to cancel the default behavior associated with
an event. Check whether
isDefaultPrevented() method.
preventDefault() has already been called on an event object, with the
The preventDefault() method works only if the event’s default behavior can be canceled. You can check whether
an event has behavior that can be canceled by referring to the API documentation, or by examining the
cancelable
property of the event object.
Canceling the default behavior has no effect on the progress of an event object through the event flow. Use the event
flow methods of the Event class to remove an event object from the event flow.
Subclasses of the Event class
For many events, the common set of properties defined in the Event class is sufficient. Representing other events,
however, requires properties not available in the Event class. For these events, the AIR API defines several subclasses
of the Event class.
Each subclass provides additional properties and event types that are unique to that category of events. For example,
events related to mouse input provide properties describing the mouse location when the event occurred. Likewise, the
InvokeEvent class adds properties containing the file path of the invoking file and any arguments passed as parameters
in the command-line invocation.
An Event subclass frequently defines additional constants to represent the event types that are associated with the
subclass. For example, the FileListEvent class defines constants for the
event types.
directoryListing and selectMultiple
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Handling HTML-related events
Handling runtime events with JavaScript
The runtime classes support adding event handlers with the addEventListener() method. To add a handler function
for an event, call the
and the handling function. For example, to listen for the
button on the title bar, use the following statement:
The type parameter of the addEventListener() method is a string, but the AIR APIs define constants for all runtime
event types. Using these constants can help pinpoint typographic errors entered in the type parameter more quickly
than using the string version.
Creating an event handler function
The following code creates a simple HTML file that displays information about the position of the main window. A
handler function named
of the main window.
addEventListener() method of the object that dispatches the event, providing the event type
closing event dispatched when a user clicks the window close
moveHandler(), listens for a move event (defined by the NativeWindowBoundsEvent class)
86
When a user moves the window, the textarea elements display the updated X and Y positions of the window:
Notice that the event object is passed as an argument to the moveHandler() method. The event parameter allows your
handler function to examine the event object. In this example, you use the event object's
the event is a
move event.
type property to report that
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Handling HTML-related events
Note: Do not use parentheses when you specify the listener parameter. For example, the moveHandler() function is
specified without parentheses in the following call to the
addEventListener(Event.MOVE, moveHandler).
addEventListener() method:
The addEventListener() method has three other parameters, described in the Adobe AIR Language Reference for
HTML Developers; these parameters are
useCapture, priority, and useWeakReference.
Removing event listeners
You can use the removeEventListener() method to remove an event listener that you no longer need. It is a good
idea to remove any listeners that will no longer be used. Required parameters include the
parameters, which are the same as the required parameters for the
addEventListener() method.
eventName and listener
Removing event listeners in HTML pages that navigate
When HTML content navigates, or when HTML content is discarded because a window that contains it is closed, the
event listeners that reference objects on the unloaded page are not automatically removed. When an object dispatches
an event to a handler that has already been unloaded, you see the following error message: "The application attempted
to reference a JavaScript object in an HTML page that is no longer loaded."
To avoid this error, remove JavaScript event listeners in an HTML page before it goes away. In the case of page
navigation (within an HTMLLoader object), remove the event listener during the
unload event of the window object.
87
For example, the following JavaScript code removes an event listener for an uncaughtScriptException event:
To prevent the error from occurring when closing windows that contain HTML content, call a cleanup function in
response to the
JavaScript code removes an event listener for an
window.nativeWindow.addEventListener(air.Event.CLOSING, cleanup);
function cleanup()
{
window.htmlLoader.removeEventListener('uncaughtScriptException',
uncaughtScriptExceptionHandler);
}
closing event of the NativeWindow object (window.nativeWindow). For example, the following
uncaughtScriptException event:
You can also prevent this error from occurring by removing an event listener as soon as it runs. For example, the
following JavaScript code creates an html window by calling the
class and adds an event listener for the
event listener using the
var html = runtime.flash.html.HTMLLoader.createRootWindow(true);
html.addEventListener('complete', htmlCompleteListener);
function htmlCompleteListener()
{
html.removeEventListener(complete, arguments.callee)
// handler code..
}
html.load(new runtime.flash.net.URLRequest("second.html"));
removeEventListener() function:
complete event. When the complete event handler is called, it removes its own
createRootWindow() method of the HTMLLoader
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Handling HTML-related events
Removing unneeded event listeners also allows the system garbage collector to reclaim any memory associated with
those listeners.
Checking for existing event listeners
The hasEventListener() method lets you check for the existence of an event listener on an object.
Error events without listeners
Exceptions, rather than events, are the primary mechanism for error handling in the runtime classes. However,
exception handling does not work for asynchronous operations such as loading files. If an error occurs during an
asynchronous operation, the runtime dispatches an error event object. If you do not create a listener for the error event,
the AIR Debug Launcher presents a dialog box with information about the error.
Most error events are based on the ErrorEvent class, and have a property named text that is used to store a descriptive
error message. An exception is the StatusEvent class, which has a
the value of the
level property is error, the StatusEvent is considered to be an error event.
An error event does not cause an application to stop executing. It manifests only as a dialog box on the AIR Debug
Launcher. It does not manifest at all in the installed AIR application running in the runtime.
level property instead of a text property. When
88
Last updated12/9/2009
Chapter 13: Scripting the HTML
Container
The HTMLLoader class serves as the container for HTML content in Adobe® AIR®. The class provides many properties
and methods for controlling the behavior and appearance of the object on the ActionScript® 3.0 display list. In
addition, the class defines properties and methods for such tasks as loading and interacting with HTML content and
managing history.
The HTMLHost class defines a set of default behaviors for an HTMLLoader. When you create an HTMLLoader object,
no HTMLHost implementation is provided. Thus when HTML content triggers one of the default behaviors, such as
changing the window location, or the window title, nothing happens. You can extend the HTMLHost class to define
the behaviors desired for your application.
A default implementation of the HTMLHost is provided for HTML windows created by AIR. You can assign the
default HTMLHost implementation to another HTMLLoader object by setting the
using a new HTMLHost object created with the
The HTMLHost class can only be extended using ActionScript. In an HTML-based application, you can import a
compiled SWF file containing an implementation of the HTMLHost class. Assign the host class implementation using
window.htmlLoader.htmlHost = new window.runtime.HTMLHostImplementation();
</script>
Display properties of HTMLLoader objects
An HTMLLoader object inherits the display properties of the Adobe® Flash® Player Sprite class. You can resize, move,
hide, and change the background color, for example. Or you can apply advanced effects like filters, masks, scaling, and
rotation. When applying effects, consider the impact on legibility. SWF and PDF content loaded into an HTML page
cannot be displayed when some effects are applied.
HTML windows contain an HTMLLoader object that renders the HTML content. This object is constrained within
the area of the window, so changing the dimensions, position, rotation, or scale factor does not always produce
desirable results.
Basic display properties
The basic display properties of the HTMLLoader allow you to position the control within its parent display object, to
set the size, and to show or hide the control. You should not change these properties for the HTMLLoader object of an
HTML window.
The basic properties include:
Last updated12/9/2009
PropertyNotes
x, yPositions the object within its parent container.
width, heightChanges the dimensions of the display area.
visibleControls the visibility of the object and any content it contains.
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Scripting the HTML Container
Outside an HTML window, the width and height properties of an HTMLLoader object default to 0. You must set the
width and height before the loaded HTML content can be seen. HTML content is drawn to the HTMLLoader size, laid
out according to the HTML and CSS properties in the content. Changing the HTMLLoader size reflows the content.
When loading content into a new HTMLLoader object (with width still set to 0), it can be tempting to set the display
width and height of the HTMLLoader using the contentWidth and contentHeight properties. This technique
works for pages that have a reasonable minimum width when laid out according the HTML and CSS flow rules.
However, some pages flow into a long and narrow layout in the absence of a reasonable width provided by the
HTMLLoader.
Note: When you change the width and height of an HTMLLoader object, the scaleX and scaleY values do not change, as
would happen with most other types of display objects.
Transparency of HTMLLoader content
The paintsDefaultBackground property of an HTMLLoader object, which is true by default, determines whether
the HTMLLoader object draws an opaque background. When
is clear. The display object container or other display objects below the HTMLLoader object are visible behind the
foreground elements of the HTML content.
paintsDefaultBackground is false, the background
90
If the body element or any other element of the HTML document specifies a background color (using
style="background-color:gray", for example), then the background of that portion of the HTML is opaque and
rendered with the specified background color. If you set the
paintsDefaultBackground is false, then the color set for the opaqueBackground is visible.
and
opaqueBackground property of the HTMLLoader object,
Note: You can use a transparent, PNG-format graphic to provide an alpha-blended background for an element in an
HTML document. Setting the opacity style of an HTML element is not supported.
Scaling HTMLLoader content
Avoid scaling an HTMLLoader object beyond a scale factor of 1.0. Text in HTMLLoader content is rendered at a
specific resolution and appears pixelated if the HTMLLoader object is scaled up.
Considerations when loading SWF or PDF content in an HTML page
SWF and PDF content loaded into in an HTMLLoader object disappears in the following conditions:
• If you scale the HTMLLoader object to a factor other that 1.0.
• If you set the alpha property of the HTMLLoader object to a value other than 1.0.
• If you rotate the HTMLLoader content.
The content reappears if you remove the offending property setting and remove the active filters.
Note: The runtime cannot display SWF or PDF content in transparent windows.
For more information on loading these types of media in an HTMLLoader, see “Embedding SWF content in HTML”
on page 59and “Adding PDF content” on page 293.
Last updated12/9/2009
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
Scripting the HTML Container
Advanced display properties
The HTMLLoader class inherits several methods that can be used for special effects. In general, these effects have
limitations when used with the HTMLLoader display, but they can be useful for transitions or other temporary effects.
For example, if you display a dialog window to gather user input, you could blur the display of the main window until
the user closes the dialog. Likewise, you could fade the display out when closing a window.
The advanced display properties include:
PropertyLimitations
alphaCan reduce the legibility of HTML content
filtersIn an HTML Window, exterior effects are clipped by the window edge
91
graphicsShapes drawn with graphics commands appear below HTML content,
opaqueBackgroundDoes not change the color of the default background. The
rotationThe corners of the rectangular HTMLLoader area can be clipped by the
scaleX, scaleYThe rendered display can appear pixelated at scale factors greater than 1. SWF
transformCan reduce legibility of HTML content. The HTML display can be clipped by the
including the default background. The paintsDefaultBackground property
must be false for the drawn shapes to be visible.
paintsDefaultBackground property must be false for this color layer to be
visible.
window edge. SWF and PDF content loaded in the HTML content is not
displayed.
and PDF content loaded in the HTML content is not displayed.
window edge. SWF and PDF content loaded in the HTML content is not
displayed if the transform involves rotation, scaling, or skewing.
The following example illustrates how to set the filters array to blur the entire HTML display:
var blur = new window.runtime.flash.filters.BlurFilter();
var filters = [blur];
window.htmlLoader.filters = filters;
Note: Display object classes, such as Sprite and BlurFilter, are not commonly used in HTML-based applications. They are
not listed in the
Adobe AIR Language Reference for HTML Developers (http://www.adobe.com/go/learn_air_html_jslr)
nor aliased in the AIRAliases.js file. For documentation about these classes, you can refer to the Flex 3 Language
Reference.
Accessing the HTML history list
As new pages are loaded in an HTMLLoader object, the runtime maintains a history list for the object. The history list
corresponds to the
properties and methods that let you work with the HTML history list:
Class memberDescription
historyLengthThe overall length of the history list, including back and forward entries.
historyPositionThe current position in the history list. History items before this position represent “back” navigation, and
getHistoryAt()Returns the URLRequest object corresponding to the history entry at the specified position in the history list.
window.history object in the HTML page. The HTMLLoader class includes the following
items after this position represent “forward” navigation.
Last updated12/9/2009
Class memberDescription
historyBack()Navigates back in the history list, if possible.
historyForward()Navigates forward in the history list, if possible.
DEVELOPING ADOBE AIR 1.5 APPLICATIONS WITH HTML AND AJAX
92
Scripting the HTML Container
historyGo()Navigates the indicated number of steps in the browser history. Navigates forward if positive, backward if
negative. Navigating to zero reloads the page. Specifying a position beyond the end navigates to the end of
the list.
Items in the history list are stored as objects of type HistoryListItem. The HistoryListItem class has the following
properties:
PropertyDescription
isPostSet to true if the HTML page includes POST data.
originalUrlThe original URL of the HTML page, before any redirects.
titleThe title of the HTML page.
urlThe URL of the HTML page.
Setting the user agent used when loading HTML content
The HTMLLoader class has a userAgent property, which lets you set the user agent string used by the HTMLLoader.
userAgent property of the HTMLLoader object before calling the load() method. If you set this property on
Set the
the HTMLLoader instance, then the
You can set the default user agent string used by all HTMLLoader objects in an application domain by setting the
URLRequestDefaults.userAgent property. The static URLRequestDefaults properties apply as defaults for all
URLRequest objects, not only URLRequests used with the
userAgent property of an HTMLLoader overrides the default URLRequestDefaults.userAgent setting.
userAgent property of the URLRequest passed to the load() method is not used.
load() method of HTMLLoader objects. Setting the
If you do not set a user agent value for either the userAgent property of the HTMLLoader object or for
URLRequestDefaults.userAgent, then the default AIR user agent value is used. This default value varies depending
on the runtime operating system (such as Mac OS or Windows), the runtime language, and the runtime version, as in
the following two examples:
• "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko)
AdobeAIR/1.0"
• "Mozilla/5.0 (Windows; U; en) AppleWebKit/420+ (KHTML, like Gecko) AdobeAIR/1.0"
Setting the character encoding to use for HTML content
An HTML page can specify the character encoding it uses by including meta tag, such as the following:
meta http-equiv="content-type" content="text/html" charset="ISO-8859-1";
Override the page setting to ensure that a specific character encoding is used by setting the textEncodingOverride
property of the HTMLLoader object: