Macromedia Air User Manual

HTML Developer’s Guide for
ADOBE® AIR®

Legal notices

Legal notices
Last updated 9/28/2011

Contents

Chapter 1: About the HTML environment
Overview of the HTML environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
AIR and WebKit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Chapter 2: Programming HTML and JavaScript in AIR
Creating an HTML-based AIR application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
An example application and security implications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Avoiding security-related JavaScript errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Accessing AIR API classes from JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
About URLs in AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Embedding SWF content in HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Using ActionScript libraries within an HTML page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Converting Date and RegExp objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Cross-scripting content in different security sandboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
iii
Chapter 3: Handling HTML-related events in AIR
HTMLLoader events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
How AIR class-event handling differs from other event handling in the HTML DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Adobe AIR event objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Handling runtime events with JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Chapter 4: Scripting the AIR HTML Container
Display properties of HTMLLoader objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Accessing the HTML history list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Setting the user agent used when loading HTML content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Setting the character encoding to use for HTML content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Defining browser-like user interfaces for HTML content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Chapter 5: Working with vectors
Basics of vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Creating vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Inserting elements into a vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Retrieving values and removing vector elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Properties and methods of Vector objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Example: Using AIR APIs that require vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Chapter 6: AIR security
AIR security basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Installation and updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
HTML security in Adobe AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Scripting between content in different domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Writing to disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Working securely with untrusted content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Contents
Best security practices for developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Code signing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Chapter 7: Working with AIR native windows
Basics of native windows in AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Creating windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Managing windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Listening for window events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Displaying full-screen windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Chapter 8: Display screens in AIR
Basics of display screens in AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Enumerating the screens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Chapter 9: Working with menus
Menu basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Creating native menus (AIR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
About context menus in HTML (AIR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Displaying pop-up native menus (AIR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Handling menu events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Native menu example: Window and application menu (AIR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Using the MenuBuilder framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
iv
Chapter 10: Taskbar icons in AIR
About taskbar icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Dock icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
System Tray icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Window taskbar icons and buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Chapter 11: Working with the file system
Using the AIR file system API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Chapter 12: Drag and drop in AIR
Drag and drop in HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Dragging data out of an HTML element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Dragging data into an HTML element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Example: Overriding the default HTML drag-in behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Handling file drops in non-application HTML sandboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Dropping file promises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Chapter 13: Copy and paste
Basics of copy-and-paste . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Reading from and writing to the system clipboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
HTML copy and paste in AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Clipboard data formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Chapter 14: Working with local SQL databases in AIR
About local SQL databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Creating and modifying a database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Contents
Manipulating SQL database data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Using synchronous and asynchronous database operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Using encryption with SQL databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Strategies for working with SQL databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Chapter 15: Encrypted local storage
Adding data to the encrypted local store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Accessing data in the encrypted local store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Removing data from the encrypted local store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Chapter 16: Working with byte arrays
Reading and writing a ByteArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
ByteArray example: Reading a .zip file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Chapter 17: Adding PDF content in AIR
Detecting PDF Capability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Loading PDF content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Scripting PDF content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Known limitations for PDF content in AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
v
Chapter 18: Working with sound
Basics of working with sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Understanding the sound architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Loading external sound files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Working with embedded sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Working with streaming sound files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Working with dynamically generated audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Playing sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Working with sound metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Accessing raw sound data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Capturing sound input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Chapter 19: Client system environment
Basics of the client system environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Using the System class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Using the Capabilities class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Chapter 20: AIR application invocation and termination
Application invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Capturing command line arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Invoking an AIR application on user login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Invoking an AIR application from the browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Application termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Chapter 21: Working with AIR runtime and operating system information
Managing file associations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Getting the runtime version and patch level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Detecting AIR capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Tracking user presence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Contents
Chapter 22: Sockets
TCP sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
UDP sockets (AIR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
IPv6 addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Chapter 23: HTTP communications
Loading external data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Web service requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Opening a URL in another application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Sending a URL to a server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Chapter 24: Communicating with other Flash Player and AIR instances
About the LocalConnection class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Sending messages between two applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Connecting to content in different domains and to AIR applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Chapter 25: ActionScript basics for JavaScript developers
Differences between ActionScript and JavaScript: an overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
ActionScript 3.0 data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
ActionScript 3.0 classes, packages, and namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Required parameters and default values in ActionScript 3.0 functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
ActionScript 3.0 event listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
vi
Chapter 26: SQL support in local databases
Supported SQL syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Data type support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Chapter 27: SQL error detail messages, ids, and arguments
Last updated 9/28/2011

Chapter 1: About the HTML environment

Adobe AIR 1.0 and later
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.
The following table lists the version of WebKit used in each release of AIR. The closest corresponding release of the Safari web browser is also given:
1
AIR version WebKit version Safari version
1.0 420 2.04
1.1 523 3.04
1.5 526.9 4.0 Beta
2.0 531.9 4.03
2.5 531.9 4.03
2.6 531.9 4.03
You can always determine the installed version of WebKit by examining the default user agent string returned by a HTMLLoader object:
air.trace( window.htmlLoader.userAgent );
Keep in mind that the version of WebKit used in AIR is not identical to the open source version. Some features are not supported in AIR and the AIR version can include security and bug fixes not yet available in the corresponding WebKit version. See
WebKit features not supported in AIR” on page 16.
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).
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
HTML content in AIR does not display SWF or PDF content if alpha, scaling, or transparency settings are applied. For more information, see “Window transparency” on page 87.
Considerations when loading SWF or PDF content in an HTML page” on page 48 and
More Help topics
Webkit DOM Reference
Safari HTML Reference
Safari CSS Reference
www.webkit.org

Overview of the HTML environment

Adobe AIR 1.0 and later
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.
2

About the JavaScript environment and its relationship to the AIR host

Adobe AIR 1.0 and later
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.)
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
AIR Run-time Environment
NativeWindow
HTMLLoader
window
JavaScript Environment
window
3
document
body
h1 divptable
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
nativeWindow
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.
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
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

Adobe AIR 1.0 and later
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 run­time 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
4
Another way to allow application and non-application content to cross-script each other, and the only way to give non­application 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 in Adobe AIR” on page 73 and “HTML
frame and iframe elements” on page 12.

About plug-ins and embedded objects

Adobe AIR 1.0 and later
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 in Adobe AIR” on page 73
HTML Sandboxes” on page 5
HTML frame and iframe elements” on page 12
JavaScript Window object” on page 10
The XMLHttpRequest object” on page 6
Adding PDF content in AIR” on page 270
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment

AIR and WebKit

Adobe AIR 1.0 and later
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 web site. Mozilla also provides a valuable general referenceon HTML, CSS, and DOM topics (of course, the WebKit and Mozilla engines are not identical).

JavaScript in AIR

Flash Player 9 and later, Adobe AIR 1.0 and later
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 22.
www.webkit.org and developer.apple.com. For standards
Avoiding security-related JavaScript errors
5
HTML Sandboxes
Adobe AIR 1.0 and later
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 Security sandboxes for more information on the types of sandboxes you may encounter when 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-file system 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.
app: URL scheme) is placed in the application
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
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
Adobe AIR 1.0 and later
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 76 describes the allowed
uses of the eval() function.
Function constructors
Adobe AIR 1.0 and later
6
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
Adobe AIR 1.0 and later
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.
The XMLHttpRequest object
Adobe AIR 1.0 and later
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
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 non­application sandbox by setting
allowCrossDomainXHR, an attribute added by AIR, to true in the containing frame or
iframe element:
<iframe id="mashup" src="http://www.example.com/map.html" allowCrossDomainXHR="true" </iframe>
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:
<iframe id="mashup" src="http://www.example.com/map.html" documentRoot="app:/sandbox/" sandboxRoot="http://www.example.com/" allowCrossDomainXHR="true" </iframe>
7
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:
<iframe id="mashup" src="http://www.example.com/map.html" documentRoot="app:/sandbox/" sandboxRoot="http://www.example.com/air/" allowCrossDomainXHR="true" </iframe>
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 12 and “HTML security
in Adobe AIR” on page 73.
Cookies
Adobe AIR 1.0 and later
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, other means for storing persistent data are available,
(the including the EncryptedLocalStore, SharedObject, and FileStream classes.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
The Clipboard object
Adobe AIR 1.0 and later
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:
Method Description
clearData(mimeType) Clears the clipboard data. Set the mimeType parameter to the MIME type of the data to clear.
clipboardData property. Use the following methods of the
8
getData(mimeType) Get the clipboard data. This method can only be called in a handler for the paste event. Set the mimeType
setData(mimeType, data) Copy data to the clipboard. Set the mimeType parameter to the MIME type of the data.
parameter to the MIME type of the data to return.
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:
MIME type Value
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"
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 195 and Using the Pasteboard from
JavaScript (Apple Developer Center).
Drag and Drop
Adobe AIR 1.0 and later
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
function onDrop(dragEvent){ return dragEvent.dataTransfer.getData("text/plain", air.ClipboardTransferMode.ORIGINAL_ONLY); }
The dataTransfer object has the following important members:
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:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
Member Description
clearData(mimeType) Clears the data. Set the mimeType parameter to the MIME type of the data representation to clear.
9
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.
types An array of strings containing the MIME types of all data representations currently available in the
effectsAllowed Specifies whether the data being dragged can be copied, moved, linked, or some combination thereof. Set the
dropEffect Specifies 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 in AIR” on page 177 and Using the Drag-and-Drop from JavaScript (Apple Developer Center).
innerHTML and outerHTML properties
Adobe AIR 1.0 and later
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 in Adobe AIR” on page 73.
<script> tags are not
Document.write() and Document.writeln() methods
Adobe AIR 1.0 and later
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
Adobe AIR 1.0 and later
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 14 for additional information.
Last updated 9/28/2011
designMode to on is equivalent to setting the
HTML contentEditable attribute” on
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
unload events (for body and frameset objects)
Adobe AIR 1.0 and later
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
Adobe AIR 1.0 and later
10
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();
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 28.
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
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
the control paints a default, white background:
window.htmlLoader.paintsDefaultBackground = false;
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
Cross-scripting content in different security sandboxes” on page 34.
setTimeout() or setInterval(). You must use a function reference. For more
setTimeout() and setInterval()” on page 25.
11
Window.open() function When called by code running in a non-application sandbox, the open() method only opens
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 78.
air.NativeApplication object
Adobe AIR 1.0 and later
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.
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. For more information about the NativeApplication object, see
Working with AIR runtime and operating system information” on page 304.
The JavaScript URL scheme
Adobe AIR 1.0 and later
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment

HTML in AIR

Adobe AIR 1.0 and later
AIR and WebKit define a couple of non-standard HTML elements and attributes, including:
HTML frame and iframe elements” on page 12
HTML element event handlers” on page 14
HTML frame and iframe elements
Adobe AIR 1.0 and later
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).
src attribute. The file is loaded into the non-application sandbox corresponding to the specified
12
documentRoot attribute The documentRoot attribute specifies the local directory from which to load URLs that
resolve to files within the location specified by
sandboxRoot.
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
sandboxRoot is replaced with the value specified in documentRoot. Thus, in the
following frame tag:
<iframe src="http://www.example.com/air/child.html" documentRoot="app:/sandbox/" sandboxRoot="http://www.example.com/air/"/>
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.
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 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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
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 non­application 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:
<iframe src="http://localhost/air/child.html" documentRoot="app:/sandbox/" sandboxRoot="http://localhost/air/"/>
Place child.html in a remote sandbox, allowing XMLHttpRequests only to www.example.com:
<iframe src="http://www.example.com/air/child.html" documentRoot="app:/sandbox/" sandboxRoot="http://www.example.com/air/"/>
Place child.html in a remote sandbox, allowing XMLHttpRequests to any remote domain:
<iframe src="http://www.example.com/air/child.html" documentRoot="app:/sandbox/" sandboxRoot="http://www.example.com/air/" allowCrossDomainXHR="allowCrossDomainXHR"/>
13
Place child.html in a local-with-file-system sandbox:
<iframe src="file:///templates/child.html" documentRoot="app:/sandbox/" sandboxRoot="app-storage:/templates/"/>
Place child.html in a remote sandbox, using the dominitialize event to establish a sandbox bridge:
<html> <head> <script> var bridgeInterface = {}; bridgeInterface.testProperty = "Bridge engaged"; function engageBridge(){ document.getElementById("sandbox").parentSandboxBridge = bridgeInterface; } </script> </head> <body> <iframe id="sandbox" src="http://www.example.com/air/child.html" documentRoot="app:/" sandboxRoot="http://www.example.com/air/" ondominitialize="engageBridge()"/> </body> </html>
The following child.html document illustrates how child content can access the parent sandbox bridge:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
<html> <head> <script> document.write(window.parentSandboxBridge.testProperty); </script> </head> <body></body> </html>
For more information, see “Cross-scripting content in different security sandboxes” on page 34 and “HTML security
in Adobe AIR” on page 73.
HTML element event handlers
Adobe AIR 1.0 and later
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 name Description
14
oncontextmenu Called when a context menu is invoked, such as through a right-click
oncopy Called when a selection in an element is copied.
oncut Called when a selection in an element is cut.
ondominitialize Called when the DOM of a document loaded in a frame or iframe is
ondrag Called when an element is dragged.
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.
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.
or command-click on selected text.
created, but before any DOM elements are created or scripts parsed.
element.
onselectstart Called when a selection begins.
HTML contentEditable attribute
Adobe AIR 1.0 and later
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
Last updated 9/28/2011
p element:
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
<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>
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 9 for additional
information.
Data: URLs
Adobe AIR 2 and later
AIR supports data: URLs for the following elements:
img
input type=”image”
CSS rules allowing images (such as background-image)
Data URLs allow you to insert binary image data directly into a CSS or HTML document as a base64-encoded string. The following example uses a data: URL as a repeating background:
15
<html> <head> <style> body { background­image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAMAAABHPGVmAAAAGXRFWHRTb2Z 0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRF%2F6cA%2F%2F%2F%2Fgxp3lwAAAAJ0Uk5T%2FwDltzBKAAA BF0lEQVR42uzZQQ7CMAxE0e%2F7X5oNCyRocWzPiJbMBZ6qpIljE%2BnwklgKG7kwUjc2IkIaxkY0CPdEsCCasws6ShX BgmBBmEagpXQQLAgWBAuSY2gaKaWPYEGwIEwg0FRmECwIFoQeQjJlhJWUEFazjFDJCkI5WYRWMgjtfEGYyQnCXD4jTCd m1zmngFpBFznwVNi5RPSbwbWnpYr%2BBHi%2FtCTfgPLEPL7jBctAKBRptXJ8M%2BprIuZKu%2BUKcg4YK1PLz7kx4bS qHyPaT4d%2B28OCJJiRBo4FCQsSA0bziT3XubMgYUG6fc5fatmGBQkL0hoJ1IaZMiQsSFiQ8vRscTjlQOI2iHZwtpHuf %2BJAYiOiJSkj8Z%2FIQ4ABANvXGLd3%2BZMrAAAAAElFTkSuQmCC'); background-repeat:repeat; } </style> </head> <body> </body> </html>
When using data: URLS, be aware that extra whitespace is significant. For example, the data string must be entered as a single, unbroken line. Otherwise, the line breaks are treated as part of the data and the image cannot be decoded.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment

CSS in AIR

Adobe AIR 1.0 and later
WebKit supports several extended CSS properties. Many of these extensions use the prefix: -webkit. Note that some of these extensions are experimental in nature and may be removed from a future version of WebKit. For more information about the Webkit support for CSS and its extensions to CSS, see
Safari CSS Reference.

WebKit features not supported in AIR

Adobe AIR 1.0 and later
AIR does not support the following features available in WebKit or Safari 4:
Cross-domain messaging via window.postMessage (AIR provides its own cross-domain communication APIs)
CSS variables
Web Open Font Format (WOFF) and SVG fonts.
HTML video and audio tags
Media device queries
Offline application cache
Printing (AIR provides its own PrintJob API)
Spelling and grammar checkers
SVG
WAI-ARIA
WebSockets (AIR provides its own socket APIs)
Web workers
WebKit SQL API (AIR provides its own API)
WebKit geolocation API (AIR provides its own geolocation API on supported devices)
WebKit multi-file upload API
WebKit touch events (AIR provides its own touch events)
Wireless Markup Language (WML)
The following lists contain specific JavaScript APIs, HTML elements, and CSS properties and values that AIR does not support:
16
Unsupported JavaScript Window object members:
applicationCache()
console
openDatabase()
postMessage()
document.print()
Unsupported HTML tags:
audio
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
video
Unsupported HTML attributes:
aria-*
draggable
formnovalidate
list
novalidate
onbeforeload
onhashchange
onorientationchange
onpagehide
onpageshow
onpopstate
ontouchstart
ontouchmove
ontouchend
ontouchcancel
onwebkitbeginfullscreen
onwebkitendfullscreen
pattern
required
sandbox
17
Unsupported JavaScript events:
beforeload
hashchange
orientationchange
pagehide
pageshow
popstate
touchstart
touchmove
touchend
touchcancel
webkitbeginfullscreen
webkitendfullscreen
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
Unsupported CSS properties:
background-clip
background-origin (use -webkit-background-origin)
background-repeat-x
background-repeat-y
background-size (use -webkit-background-size)
border-bottom-left-radius
border-bottom-right-radius
border-radius
border-top-left-radius
border-top-right-radius
text-rendering
-webkit-animation-play-state
-webkit-background-clip
-webkit-color-correction
-webkit-font-smoothing
18
Unsupported CSS values:
appearance property values:
media-volume-slider-container
media-volume-slider
media-volume-sliderthumb
outer-spin-button
border-box (background-clip and background-origin)
contain (background-size)
content-box (background-clip and background-origin)
cover (background-size)
list property values:
afar
amharic
amharic-abegede
cjk-earthly-branch
cjk-heavenly-stem
ethiopic
ethiopic-abegede
ethiopic-abegede-am-et
ethiopic-abegede-gez
ethiopic-abegede-ti-er
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
About the HTML environment
ethiopic-abegede-ti-et
ethiopic-halehame-aa-er
ethiopic-halehame-aa-et
ethiopic-halehame-am-et
ethiopic-halehame-gez
ethiopic-halehame-om-et
ethiopic-halehame-sid-et
ethiopic-halehame-so-et
ethiopic-halehame-ti-er
ethiopic-halehame-ti-et
ethiopic-halehame-tig
hangul
hangul-consonant
lower-norwegian
oromo
sidama
somali
tigre
tigrinya-er
tigrinya-er-abegede
tigrinya-et
tigrinya-et-abegede
upper-greek
upper-norwegian
-wap-marquee (display property)
19
Last updated 9/28/2011

Chapter 2: Programming HTML and JavaScript in AIR

Adobe AIR 1.0 and later
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

Adobe AIR 1.0 and later
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.
20
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.
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR

An example application and security implications

Adobe AIR 1.0 and later
The following HTML code uses uses the filesystem APIs to list the files and directories in the user’s desktop directory.
Here’s the HTML code for the application:
21
<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.
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 28.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
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

Adobe AIR 1.0 and later
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
eval() function and related APIs.
22
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 Security sandboxes). By default, content installed with the application is 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.
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 34.
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 22.
For more information, see “HTML security in Adobe AIR” on page 73.

Avoiding security-related JavaScript errors

Adobe AIR 1.0 and later
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 updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR

Causes of security-related JavaScript errors

Adobe AIR 1.0 and later
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 76for more information.
load event has fired and any load event handlers have exited. Attempting to use the
23
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

Adobe AIR 1.0 and later
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 36.
Loading application content into a non-application sandbox” on page 35. If that content also

eval() function

Flash Player 9 and later, Adobe AIR 1.0 and later
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().
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR

Assigning properties to an object

Adobe AIR 1.0 and later
Instead of parsing a string to build the property accessor:
eval("obj." + propName + " = " + val);
access properties with bracket notation:
obj[propName] = val;

Creating a function with variables available in context

Adobe AIR 1.0 and later
Replace statements such as the following:
function compile(var1, var2){ eval("var fn = function(){ this."+var1+"(var2) }"); return fn; }
with:
24
function compile(var1, var2){ var self = this; return function(){ self[var1](var2) }; }

Creating an object using the name of the class as a string parameter

Adobe AIR 1.0 and later
Consider a hypothetical JavaScript class defined with the following code:
var CustomClass = { Utils: { Parser: function(){ alert('constructor') } }, Data: {
} }; var constructorClassName = "CustomClass.Utils.Parser";
The simplest way to create a instance would be to use eval():
var myObj; eval('myObj=new ' + constructorClassName +'()')
However, you could avoid the call to eval() by parsing each component of the class name and building the new object using bracket notation:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
function getter(str) { var obj = window; var names = str.split('.'); for(var i=0;i<names.length;i++){ if(typeof obj[names[i]]=='undefined'){ var undefstring = names[0]; for(var j=1;j<=i;j++) undefstring+="."+names[j]; throw new Error(undefstring+" is undefined"); } obj = obj[names[i]]; } return obj; }
To create the instance, use:
try{ var Parser = getter(constructorClassName); var a = new Parser(); }catch(e){ alert(e); }
25

setTimeout() and setInterval()

Adobe AIR 1.0 and later
Replace the string passed as the handler function with a function reference or object. For example, replace a statement such as:
setTimeout("alert('Timeout')", 100);
with:
setTimeout(function(){alert('Timeout')}, 100);
Or, when the function requires the this object to be set by the caller, replace a statement such as:
this.appTimer = setInterval("obj.customFunction();", 100);
with the following:
var _self = this; this.appTimer = setInterval(function(){obj.customFunction.apply(_self);}, 100);

Function constructor

Adobe AIR 1.0 and later
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
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR

javascript: URLs

Adobe AIR 1.0 and later
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

Adobe AIR 1.0 and later
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
onclick or onmouseover, are ignored. No security error is generated. Instead, you can
26
For example, given a target element in a document, such as:
<div id="container"></div>
Replace statements such as:
document.getElementById('container').innerHTML = '<a href="#" onclick="code()">Click Me.</a>';
with:
document.getElementById('container').innerHTML = '<a href="#" id="smith">Click Me.</a>'; document.getElementById('smith').addEventListener("click", function() { code(); });

Loading JavaScript files from outside the application installation directory

Adobe AIR 1.0 and later
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
Loading application content into a non-application sandbox” on
page 35.

document.write() and document.writeln()

Adobe AIR 1.0 and later
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR

Synchronous XMLHttpRequests before the load event or during a load event handler

Adobe AIR 1.0 and later
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

Dynamically created script elements

Adobe AIR 1.0 and later
Dynamically created script elements, such as when created with innerHTML or document.createElement() method are ignored.

Accessing AIR API classes from JavaScript

27
Adobe AIR 1.0 and later
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();
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 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 parent.
flash.filesystem property of the runtime object provides access to the
flash property of the runtime object provides
runtime property of the
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 includes an AIRAliases.js file that lets you access runtime classes much more easily (for instance, by simply typing
air.NativeApplication).
window.runtime.flash.desktop.NativeApplication), the AIR SDK
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
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 API 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.
Note: For more information, see ActionScript 3.0 classes, packages, and namespaces” on page 337 and “ActionScript
basics for JavaScript developers” on page 335.

Using the AIRAliases.js file

Adobe AIR 1.0 and later
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:
28
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 API Reference for HTML Developers.
In addition to commonly used runtime classes, the AIRAliases.js file includes aliases for commonly used package­level 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>
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR

About URLs in AIR

Adobe AIR 1.0 and later
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 scheme Description Example
29
file A path relative to the root of the file system.
app A path relative to the root directory of the installed
application.
app-storage A 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.
http A standard HTTP request.
https A 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 “URI schemes” on page 318.
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 “HTTP communications” on page 316.

Embedding SWF content in HTML

Adobe AIR 1.0 and later
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.
If you have enabled transparency in the NativeWindow object displaying the HTML and SWF content, then AIR does not display the SWF content when window mode ( display SWF content in an HTML page of a transparent window, set the
window is the default value for wmode, so if you do not specify a value, your content may not be displayed.
The
wmode) used to embed the content is set to the value: window. To
wmode parameter to opaque or transparent.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
The following example illustrates the use of the HTML object tag to display a SWF file within HTML content. The
wmode parameter is set to opaque so that the content is displayed, even if the underlying NativeWindow object is
transparent. 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.)
<object type="application/x-shockwave-flash" width="100%" height="100%">
<param name="movie" value="app:/SWFFile.swf"></param> <param name="wmode" value="opaque"></param>
</object>
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); var flash = createSWFObject(urlString, 'opaque', 650, 650);
displayContainer.appendChild(flash); } function createSWFObject(urlString, wmodeString, width, height){
var SWFObject = document.createElement("object");
SWFObject.setAttribute("type","application/x-shockwave-flash");
SWFObject.setAttribute("width","100%");
SWFObject.setAttribute("height","100%");
var movieParam = document.createElement("param");
movieParam.setAttribute("name","movie");
movieParam.setAttribute("value",urlString);
SWFObject.appendChild(movieParam);
var wmodeParam = document.createElement("param");
wmodeParam.setAttribute("name","wmode");
wmodeParam.setAttribute("value",wmodeString);
SWFObject.appendChild(wmodeParam);
return SWFObject; } </script>
elementID parameter:
urlString parameter. The example adds the node as a child of the page element with the ID
30
SWF content is not displayed if the HTMLLoader object is scaled or rotated, or if the alpha property is set to a value other than 1.0. Prior to AIR 1.5.2, SWF content was not displayed in a transparent window no matter which
wmode
value was set.
Note: When an embedded SWF object attempts to load an external asset like a video file, the SWF content may not be rendered properly if an absolute path to the video file is not provided in the HTML file. However, an embedded SWF object can load an external image file using a relative path.
The following example depicts how external assets can be loaded through a SWF object embedded in an HTML content:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
var imageLoader;
function showSWF(urlString, elementID){
var displayContainer = document.getElementById(elementID); imageLoader = createSWFObject(urlString,650,650); displayContainer.appendChild(imageLoader);
}
function createSWFObject(urlString, width, height){
var SWFObject = document.createElement("object"); SWFObject.setAttribute("type","application/x-shockwave-flash"); SWFObject.setAttribute("width","100%"); SWFObject.setAttribute("height","100%");
var movieParam = document.createElement("param"); movieParam.setAttribute("name","movie"); movieParam.setAttribute("value",urlString); SWFObject.appendChild(movieParam);
var flashVars = document.createElement("param"); flashVars.setAttribute("name","FlashVars");
//Load the asset inside the SWF content. flashVars.setAttribute("value","imgPath=air.jpg"); SWFObject.appendChild(flashVars);
return SWFObject;
} function loadImage() {
showSWF("ImageLoader.swf", "imageSpot");
}
31
In the following ActionScript example, the image path passed by the HTML file is read and the image is loaded on stage:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
package { import flash.display.Sprite; import flash.display.LoaderInfo; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.display.Loader; import flash.net.URLRequest;
public class ImageLoader extends Sprite { public function ImageLoader() {
var flashvars = LoaderInfo(this.loaderInfo).parameters;
if(flashvars.imgPath){ var imageLoader = new Loader(); var image = new URLRequest(flashvars.imgPath); imageLoader.load(image); addChild(imageLoader); imageLoader.x = 0; imageLoader.y = 0; stage.scaleMode=StageScaleMode.NO_SCALE; stage.align=StageAlign.TOP_LEFT; } } } }
32

Using ActionScript libraries within an HTML page

Adobe AIR 1.0 and later
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:
<script src="lib/myClasses.swf" type="application/x-shockwave-flash"></script>
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.
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:
lib subdirectory of the root application folder,
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
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 SDK and is described in the Flex SDK documentation.

Accessing the HTML DOM and JavaScript objects from an imported ActionScript file

Adobe AIR 1.0 and later
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.
33
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:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
public function modifyDOM(window:*):void { window.document.getElementById("p1").innerHTML = "Bye"; window.foo = 66;

Converting Date and RegExp objects

Adobe AIR 1.0 and later
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);
34

Cross-scripting content in different security sandboxes

Adobe AIR 1.0 and later
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

Adobe AIR 1.0 and later
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 same­origin 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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
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.
Another cross-scripting technique lets you create an interface called a sandbox bridge between content in a non­application 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 12, “HTML security in Adobe AIR” on page 73, and “The XMLHttpRequest object” on page 6.

Loading application content into a non-application sandbox

Adobe AIR 1.0 and later
35
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
http://localhost/ or some other innocuous value,
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 application content loaded in this way is treated as if it was actually loaded from the
sandboxRoot URL are loaded instead from the documentRoot directory. For security purposes, the
sandboxRoot URL.
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
<iframe src="http://www.example.com/local/ui.html" sandboxRoot="http://www.example.com/local/" documentRoot="app:/sandbox/"> </iframe>
www.example.com domain:
The ui.html page could load a javascript file from the local, sandbox folder using the following script tag:
<script src="http://www.example.com/local/ui.js"></script>
It could also load content from a directory on the remote server using a script tag such as the following:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
<script src="http://www.example.com/remote/remote.js"></script>
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.

Setting up a sandbox bridge interface

Adobe AIR 1.0 and later
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

Adobe AIR 1.0 and later
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:
childSandbox property to a function or object in the child document.
36
var interface = {}; interface.calculatePrice = function(){ return ".45 cents"; } interface.storeID = "abc" window.childSandboxBridge = interface;
If this child content was loaded into an iframe assigned an id of “child”, you could access the interface from parent content by reading the
var childInterface = document.getElementById("child").contentWindow.childSandboxBridge; air.trace(childInterface.calculatePrice()); //traces ".45 cents" air.trace(childInterface.storeID)); //traces "abc"
childSandboxBridge property of the frame:

Establishing a parent sandbox bridge

Adobe AIR 1.0 and later
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:
parentSandbox property of the child document to a
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
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.

Accessing a parent sandbox bridge during page loading

Adobe AIR 1.0 and later
37
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
dominitialize event when a new page DOM has been created,
dominitialize event to establish
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:
<html> <head> <script> var bridgeInterface = {}; bridgeInterface.testProperty = "Bridge engaged"; function engageBridge(){ document.getElementById("sandbox").contentWindow.parentSandboxBridge = bridgeInterface; } </script> </head> <body> <iframe id="sandbox" src="http://www.example.com/air/child.html" documentRoot="app:/" sandboxRoot="http://www.example.com/air/" ondominitialize="engageBridge()"/> </body> </html>
The following child.html document illustrates how child content can access the parent sandbox bridge:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Programming HTML and JavaScript in AIR
<html> <head> <script> document.write(window.parentSandboxBridge.testProperty); </script> </head> <body></body> </html>
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.
38
Last updated 9/28/2011

Chapter 3: Handling HTML-related events in AIR

Adobe AIR 1.0 and later
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

Adobe AIR 1.0 and later
An HTMLLoader object dispatches the following Adobe® ActionScript® 3.0 events:
39
Event Description
htmlDOMInitialize Dispatched when the HTML document is created, but before any scripts are parsed or
complete Dispatched when the HTML DOM has been created in response to a load operation,
htmlBoundsChanged Dispatched when one or both of the contentWidth and contentHeight
locationChange Dispatched when the location property of the HTMLLoader has changed.
locationChanging Dispatched before the location of the HTMLLoader changes because of user
scroll Dispatched anytime the HTML engine changes the scroll position. Scroll events can be
uncaughtScriptException Dispatched when a JavaScript exception occurs in the HTMLLoader and the exception
DOM nodes are added to the page.
immediately after the
properties have changed.
navigation, a JavaScript call, or a redirect. The dispatched when you call the
historyForward(), or historyBack() methods.
Calling the preventDefault() method of the dispatched event object cancels navigation.
If a link is opened in the system browser, a locationChanging event is not dispatched since the HTMLLoader does not change location.
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.
locationChanging event is not
load(), loadString(), reload(), historyGo(),
# links) in the page or because of calls to the
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Handling HTML-related events in AIR

How AIR class-event handling differs from other event handling in the HTML DOM

Adobe AIR 1.0 and later
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:
document.getElementById("myDiv").addEventLister("click", clickHandler)
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.)
40
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. }
eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse);
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 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.
addEventListener() method of the source object, in essence subscribing

Default behaviors

Adobe AIR 1.0 and later
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Handling HTML-related events in AIR
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

The event flow

Adobe AIR 1.0 and later
41
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 AIR reference documentation.

Adobe AIR event objects

Adobe AIR 1.0 and later
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Handling HTML-related events in AIR

Understanding Event class properties

Adobe AIR 1.0 and later
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
Adobe AIR 1.0 and later
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
myFileStream:
fileReadHandler() listener function to respond to a complete
42
myFileStream.addEventListener(Event.COMPLETE, fileReadHandler);
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 API
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.addEventListener(Event.COMPLETE, htmlRenderHandler);
rather than:
myFileStream.addEventListener("complete", htmlRenderHandler);
Default behavior information
Adobe AIR 1.0 and later
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 43.

Understanding Event class methods

Adobe AIR 1.0 and later
There are three categories of Event class methods:
Utility methods, which can create copies of an event object or convert it to a string.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Handling HTML-related events in AIR
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
The event flow” on page 41).
Default behavior methods, which prevent default behavior or check whether it has been prevented.
Event class utility methods
Adobe AIR 1.0 and later
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.
Canceling default event behavior
Adobe AIR 1.0 and later
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
43
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

Adobe AIR 1.0 and later
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 updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Handling HTML-related events in AIR

Handling runtime events with JavaScript

Adobe AIR 1.0 and later
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:
window.nativeWindow.addEventListener(air.NativeWindow.CLOSING, handleWindowClosing);
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

Adobe AIR 1.0 and later
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)
44
<html> <script src="AIRAliases.js" /> <script> function init() { writeValues(); window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.MOVE, moveHandler); } function writeValues() { document.getElementById("xText").value = window.nativeWindow.x; document.getElementById("yText").value = window.nativeWindow.y; } function moveHandler(event) { air.trace(event.type); // move writeValues(); } </script> <body onload="init()" /> <table> <tr> <td>Window X:</td> <td><textarea id="xText"></textarea></td> </tr> <tr> <td>Window Y:</td> <td><textarea id="yText"></textarea></td> </tr> </table> </body> </html>
When a user moves the window, the textarea elements display the updated X and Y positions of the window:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Handling HTML-related events in AIR
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
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 API Reference for HTML
Developers; these parameters are useCapture, priority, and useWeakReference.
Removing event listeners
Adobe AIR 1.0 and later
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
Adobe AIR 1.0 and later
45
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.
For example, the following JavaScript code removes an event listener for an uncaughtScriptException event:
window.onunload = cleanup; window.htmlLoader.addEventListener('uncaughtScriptException', uncaughtScriptException); function cleanup() { window.htmlLoader.removeEventListener('uncaughtScriptException', uncaughtScriptExceptionHandler); }
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 (if the event only needs to be handled once). For example, the following JavaScript code creates an html window by calling the
createRootWindow() method of the HTMLLoader class and adds an event listener for the complete event. When
complete event handler is called, it removes its own event listener using the removeEventListener() function:
the
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Handling HTML-related events in AIR
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"));
Removing unneeded event listeners also allows the system garbage collector to reclaim any memory associated with those listeners.
Checking for existing event listeners
Adobe AIR 1.0 and later
The hasEventListener() method lets you check for the existence of an event listener on an object.

Error events without listeners

Adobe AIR 1.0 and later
46
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.
level property instead of a text property. When
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.
Last updated 9/28/2011

Chapter 4: Scripting the AIR HTML Container

Adobe AIR 1.0 and later
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 HTML content. 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
defaultBehavior parameter set to true.
htmlHost property of the object
47
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 property:
the
<script src="HTMLHostLibrary.swf" type="application/x-shockwave-flash"></script> <script>
window.htmlLoader.htmlHost = new window.runtime.HTMLHostImplementation();
</script>

Display properties of HTMLLoader objects

Adobe AIR 1.0 and later
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

Adobe AIR 1.0 and later
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
The basic properties include:
Property Notes
x, y Positions the object within its parent container.
width, height Changes the dimensions of the display area.
visible Controls the visibility of the object and any content it contains.
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.
48

Transparency of HTMLLoader content

Adobe AIR 1.0 and later
The paintsDefaultBackground property of an HTMLLoader object, which is true by default, determines whether the HTMLLoader object draws an opaque background. When
paintsDefaultBackground is false, the background
is clear. The display object container or other display objects below the HTMLLoader object are visible behind the foreground elements of the HTML content.
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

Adobe AIR 1.0 and later
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

Adobe AIR 1.0 and later
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.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
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.
In addition, the runtime cannot display PDF content in transparent windows. The runtime only displays SWF content embedded in an HTML page when the Since the default value of
wmode is window, SWF content is not displayed in transparent windows unless you explicitly
wmode parameter of the object or embed tag is set to opaque or transparent.
set the wmode parameter.
Note: Prior to AIR 1.5.2, SWF embedded in HTML could not be displayed no matter which wmode value was used.
For more information on loading these types of media in an HTMLLoader, see “Embedding SWF content in HTML” on page 29and “Adding PDF content in AIR” on page 270.

Advanced display properties

Adobe AIR 1.0 and later
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.
49
The advanced display properties include:
Property Limitations
alpha Can reduce the legibility of HTML content
filters In an HTML Window, exterior effects are clipped by the window edge
graphics Shapes drawn with graphics commands appear below HTML content,
opaqueBackground Does not change the color of the default background. The
rotation The corners of the rectangular HTMLLoader area can be clipped by the
scaleX, scaleY The rendered display can appear pixelated at scale factors greater than 1. SWF
transform Can 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 API Reference for HTML Developers nor aliased in the AIRAliases.js file. For documentation
about these classes, consult the ActionScript 3.0 Reference for the Adobe Flash Platform.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container

Accessing the HTML history list

Adobe AIR 1.0 and later
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 member Description
historyLength The overall length of the history list, including back and forward entries.
window.history object in the HTML page. The HTMLLoader class includes the following
50
historyPosition The 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.
historyBack() Navigates back in the history list, if possible.
historyForward() Navigates forward in the history list, if possible.
historyGo() Navigates the indicated number of steps in the browser history. Navigates forward if positive, backward if
items after this position represent “forward” navigation.
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 HTMLHistoryItem. The HTMLHistoryItem class has the following properties:
Property Description
isPost Set to true if the HTML page includes POST data.
originalUrl The original URL of the HTML page, before any redirects.
title The title of the HTML page.
url The URL of the HTML page.

Setting the user agent used when loading HTML content

Adobe AIR 1.0 and later
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
userAgent property of the URLRequest passed to the load() method is not used.
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.
load() method of HTMLLoader objects. Setting the
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
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

Adobe AIR 1.0 and later
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:
51
window.htmlLoader.textEncodingOverride = "ISO-8859-1";
Specify the character encoding for the HTMLLoader content to use when an HTML page does not specify a setting with the
window.htmlLoader.textEncodingFallback = "ISO-8859-1";
The textEncodingOverride property overrides the setting in the HTML page. And the textEncodingOverride property and the setting in the HTML page override the
Set the textEncodingOverride property or the textEncodingFallback property before loading the HTML content.
textEncodingFallback property of the HTMLLoader object:
textEncodingFallback property.

Defining browser-like user interfaces for HTML content

Adobe AIR 1.0 and later
JavaScript provides several APIs for controlling the window displaying the HTML content. In AIR, these APIs can be overridden by implementing a custom
Important: You can only create a custom implementation of the HTMLHost class using ActionScript. You can import and use a compiled ActionScript (SWF) file containing a custom implementation in an HTML page. See
ActionScript libraries within an HTML page” on page 32 for more information about importing ActionScript libraries
into HTML.
HTMLHost class.
Using
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container

About extending the HTMLHost class

Adobe AIR 1.0 and later
The AIR HTMLHost class controls the following JavaScript properties and methods:
window.status
window.document.title
window.location
window.blur()
window.close()
window.focus()
window.moveBy()
window.moveTo()
window.open()
window.resizeBy()
window.resizeTo()
When you create an HTMLLoader object using new HTMLLoader(), the listed JavaScript properties or methods are not enabled. The HTMLHost class provides a default, browser-like implementation of these JavaScript APIs. You can also extend the HTMLHost class to customize the behavior. To create an HTMLHost object supporting the default behavior, set the
defaultBehaviors parameter to true in the HTMLHost constructor:
52
var defaultHost = new HTMLHost(true);
When you create an HTML window in AIR with the HTMLLoader class createRootWindow() method, an HTMLHost instance supporting the default behaviors is assigned automatically. You can change the host object behavior by assigning a different HTMLHost implementation to the can assign
null to disable the features entirely.
htmlHost property of the HTMLLoader, or you
Note: AIR assigns a default HTMLHost object to the initial window created for an HTML-based AIR application and any windows created by the default implementation of the JavaScript
window.open() method.

Example: Extending the HTMLHost class

Adobe AIR 1.0 and later
The following example shows how to customize the way that an HTMLLoader object affects the user interface, by extending the HTMLHost class:
Flex example:
1 Create a class that extends the HTMLHost class (a subclass).
2 Override methods of the new class to handle changes in the user interface-related settings. For example, the
following class, CustomHost, defines behaviors for calls to
window.document.title. Calls to window.open() open the HTML page in a new window, and changes to window.document.title (including the setting of the <title> element of an HTML page) set the title of that
window.
window.open() and changes to
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
package { import flash.html.*; import flash.display.StageScaleMode; import flash.display.NativeWindow; import flash.display.NativeWindowInitOptions;
public class CustomHost extends HTMLHost { import flash.html.*; override public function createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader { var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); var bounds:Rectangle = new Rectangle(windowCreateOptions.x, windowCreateOptions.y, windowCreateOptions.width, windowCreateOptions.height); var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions, windowCreateOptions.scrollBarsVisible, bounds); htmlControl.htmlHost = new HTMLHostImplementation(); if(windowCreateOptions.fullscreen){ htmlControl.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; } return htmlControl; } override public function updateTitle(title:String):void { htmlLoader.stage.nativeWindow.title = title; } } }
53
3 In the code that contains the HTMLLoader (not the code of the new subclass of HTMLHost), create an object of
the new class. Assign the new object to the
htmlHost property of the HTMLLoader. The following Flex code uses
the CustomHost class defined in the previous step:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
<?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" applicationComplete="init()"> <mx:Script> <![CDATA[ import flash.html.HTMLLoader; import CustomHost; private function init():void { var html:HTMLLoader = new HTMLLoader(); html.width = container.width; html.height = container.height; var urlReq:URLRequest = new URLRequest("Test.html"); html.htmlHost = new CustomHost(); html.load(urlReq); container.addChild(html); } ]]> </mx:Script> <mx:UIComponent id="container" width="100%" height="100%"/> </mx:WindowedApplication>
54
To test the code described here, include an HTML file with the following content in the application directory:
<html> <head> <title>Test</title> </head> <script> function openWindow() { window.runtime.trace("in"); document.title = "foo" window.open('Test.html'); window.runtime.trace("out"); } </script> <body> <a href="#" onclick="openWindow()">window.open('Test.html')</a> </body> </html>
Flash Professional example:
1 Create a Flash file for AIR. Set its document class to CustomHostExample and then save the file as
CustomHostExample.fla.
2 Create an ActionScript file called CustomHost.as containing a class that extends the HTMLHost class (a subclass).
This class overrides certain methods of the new class to handle changes in the user interface-related settings. For example, the following class, CustomHost, defines behaviors for calls to
window.document.title. Calls to the window.open() method open the HTML page in a new window, and
changes to the
window.document.title property (including the setting of the <title> element of an HTML
window.open() and changes to
page) set the title of that window.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
package { import flash.display.StageScaleMode; import flash.display.NativeWindow; import flash.display.NativeWindowInitOptions; import flash.events.Event; import flash.events.NativeWindowBoundsEvent; import flash.geom.Rectangle; import flash.html.HTMLLoader; import flash.html.HTMLHost; import flash.html.HTMLWindowCreateOptions; import flash.text.TextField;
public class CustomHost extends HTMLHost { public var statusField:TextField;
public function CustomHost(defaultBehaviors:Boolean=true) { super(defaultBehaviors); } override public function windowClose():void { htmlLoader.stage.nativeWindow.close(); } override public function createWindow( windowCreateOptions:HTMLWindowCreateOptions ):HTMLLoader { var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); var bounds:Rectangle = new Rectangle(windowCreateOptions.x, windowCreateOptions.y, windowCreateOptions.width, windowCreateOptions.height); var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions, windowCreateOptions.scrollBarsVisible, bounds); htmlControl.htmlHost = new HTMLHostImplementation(); if(windowCreateOptions.fullscreen){ htmlControl.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; } return htmlControl; } override public function updateLocation(locationURL:String):void { trace(locationURL); } override public function set windowRect(value:Rectangle):void { htmlLoader.stage.nativeWindow.bounds = value;
55
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
} override public function updateStatus(status:String):void { statusField.text = status; trace(status); } override public function updateTitle(title:String):void { htmlLoader.stage.nativeWindow.title = title + "- Example Application"; } override public function windowBlur():void { htmlLoader.alpha = 0.5; } override public function windowFocus():void { htmlLoader.alpha = 1; } } }
3 Create another ActionScript file named CustomHostExample.as to contain the document class for the application.
This class creates an HTMLLoader object and sets its host property to an instance of the CustomHost class defined in the previous step:
56
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
package { import flash.display.Sprite; import flash.html.HTMLLoader; import flash.net.URLRequest; import flash.text.TextField;
public class CustomHostExample extends Sprite { function CustomHostExample():void { var html:HTMLLoader = new HTMLLoader(); html.width = 550; html.height = 380; var host:CustomHost = new CustomHost(); html.htmlHost = host;
var urlReq:URLRequest = new URLRequest("Test.html"); html.load(urlReq);
addChild(html);
var statusTxt:TextField = new TextField(); statusTxt.y = 380; statusTxt.height = 20; statusTxt.width = 550; statusTxt.background = true; statusTxt.backgroundColor = 0xEEEEEEEE; addChild(statusTxt);
host.statusField = statusTxt; } } }
57
To test the code described here, include an HTML file with the following content in the application directory:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
<html> <head> <title>Test</title> <script> function openWindow() { document.title = "Test" window.open('Test.html'); } </script> </head> <body bgColor="#EEEEEE"> <a href="#" onclick="window.open('Test.html')">window.open('Test.html')</a> <br/><a href="#" onclick="window.document.location='http://www.adobe.com'"> window.document.location = 'http://www.adobe.com'</a> <br/><a href="#" onclick="window.moveBy(6, 12)">moveBy(6, 12)</a> <br/><a href="#" onclick="window.close()">window.close()</a> <br/><a href="#" onclick="window.blur()">window.blur()</a> <br/><a href="#" onclick="window.focus()">window.focus()</a> <br/><a href="#" onclick="window.status = new Date().toString()">window.status=new Date().toString()</a> </body> </html>
58
1 Create an ActionScript file, such as HTMLHostImplementation.as.
2 In this file, define a class extending the HTMLHost class.
3 Override methods of the new class to handle changes in the user interface-related settings. For example, the
following class, CustomHost, defines behaviors for calls to
window.document.title. Calls to window.open() open the HTML page in a new window, and changes to window.document.title (including the setting of the <title> element of an HTML page) set the title of that
window.open() and changes to
window.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
package { import flash.html.HTMLHost; import flash.html.HTMLLoader; import flash.html.HTMLWindowCreateOptions; import flash.geom.Rectangle; import flash.display.NativeWindowInitOptions; import flash.display.StageDisplayState;
public class HTMLHostImplementation extends HTMLHost{ public function HTMLHostImplementation(defaultBehaviors:Boolean = true):void{ super(defaultBehaviors); }
override public function updateTitle(title:String):void{ htmlLoader.stage.nativeWindow.title = title + " - New Host"; }
override public function createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader{ var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); var bounds:Rectangle = new Rectangle(windowCreateOptions.x, windowCreateOptions.y, windowCreateOptions.width, windowCreateOptions.height);
var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions, windowCreateOptions.scrollBarsVisible, bounds);
htmlControl.htmlHost = new HTMLHostImplementation();
if(windowCreateOptions.fullscreen){ htmlControl.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; }
return htmlControl; } } }
59
4 Compile the class into a SWF file using the acompc component compiler.
acompc -source-path . -include-classes HTMLHostImplementation -output Host.zip
Note: The acompc compiler is included with the Flex SDK (but not the AIR SDK, which is targeted for HTML developers who do not generally need to compile SWF files.) Instructions for using acompc are provided in the
Using
compc, the component compiler.
5 Open the Host.zip file and extract the Library.swf file inside.
6 Rename Library.swf to HTMLHostLibrary.swf. This SWF file is the library to import into the HTML page.
7 Import the library into the HTML page using a <script> tag:
<script src="HTMLHostLibrary.swf" type="application/x-shockwave-flash"></script>
8 Assign a new instance of the HTMLHost implementation to the HTMLLoader object of the page.
window.htmlLoader.htmlHost = new window.runtime.HTMLHostImplementation();
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
The following HTML page illustrates how to load and use the HTMLHost implementation. You can test the
updateTitle() and createWindow() implementations by clicking the button to open a new, fullscreen window.
<html> <head> <title>HTMLHost Example</title> <script src="HTMLHostLibrary.swf" type="application/x-shockwave-flash"></script> <script language="javascript"> window.htmlLoader.htmlHost = new window.runtime.HTMLHostImplementation();
function test(){ window.open('child.html', 'Child', 'fullscreen'); } </script> </head> <body> <button onClick="test()">Create Window</button> </body> </html>
To run this example, provide an HTML file named child.html in the application directory.
60

Handling changes to the window.location property

Adobe AIR 1.0 and later
Override the locationChange() method to handle changes of the URL of the HTML page. The locationChange() method is called when JavaScript in a page changes the value of
window.location. The following example simply
loads the requested URL:
override public function updateLocation(locationURL:String):void { htmlLoader.load(new URLRequest(locationURL)); }
Note: You can use the htmlLoader property of the HTMLHost object to reference the current HTMLLoader object.

Handling JavaScript calls to window.moveBy(), window.moveTo(), window.resizeTo(), window.resizeBy()

Adobe AIR 1.0 and later
Override the set windowRect() method to handle changes in the bounds of the HTML content. The set
windowRect() method is called when JavaScript in a page calls window.moveBy(), window.moveTo(), window.resizeTo(), or window.resizeBy(). The following example simply updates the bounds of the desktop
window:
override public function set windowRect(value:Rectangle):void { htmlLoader.stage.nativeWindow.bounds = value; }
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container

Handling JavaScript calls to window.open()

Adobe AIR 1.0 and later
Override the createWindow() method to handle JavaScript calls to window.open(). Implementations of the
createWindow() method are responsible for creating and returning a new HTMLLoader object. Typically, you would
display the HTMLLoader in a new window, but creating a window is not required.
The following example illustrates how to implement the createWindow() function using the
HTMLLoader.createRootWindow() to create both the window and the HTMLLoader object. You can also create a
NativeWindow object separately and add the HTMLLoader to the window stage.
override public function createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader{ var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); var bounds:Rectangle = new Rectangle(windowCreateOptions.x, windowCreateOptions.y, windowCreateOptions.width, windowCreateOptions.height); var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions, windowCreateOptions.scrollBarsVisible, bounds); htmlControl.htmlHost = new HTMLHostImplementation(); if(windowCreateOptions.fullscreen){ htmlControl.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; } return htmlControl; }
61
Note: This example assigns the custom HTMLHost implementation to any new windows created with window.open(). You can also use a different implementation or set the
htmlHost property to null for new windows, if desired.
The object passed as a parameter to the createWindow() method is an HTMLWindowCreateOptions object. The HTMLWindowCreateOptions class includes properties that report the values set in the features parameter string in the call to
HTMLWindowCreateOptions property
fullscreen fullscreen
height height
locationBarVisible location
menuBarVisible menubar
resizeable resizable
scrollBarsVisible scrollbars
statusBarVisible status
toolBarVisible toolbar
width width
x left or screenX
window.open():
Corresponding setting in the features string in the JavaScript call to window.open()
y top or screenY
The HTMLLoader class does not implement all the features that can be specified in the feature string. Your application must provide scroll bars, location bars, menu bars, status bars, and toolbars when appropriate.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container
The other arguments to the JavaScript window.open() method are handled by the system. A createWindow() implementation should not load content in the HTMLLoader object, or set the window title.

Handling JavaScript calls to window.close()

Adobe AIR 1.0 and later
Override the windowClose() to handle JavaScript calls to window.close() method. The following example closes the desktop window when the
override public function windowClose():void {
htmlLoader.stage.nativeWindow.close();
}
JavaScript calls to window.close() do not have to close the containing window. You could, for example, remove the HTMLLoader from the display list, leaving the window (which may have other content) open, as in the following code:
override public function windowClose():void {
htmlLoader.parent.removeChild(htmlLoader);
}
window.close() method is called:
62

Handling changes of the window.status property

Adobe AIR 1.0 and later
Override the updateStatus() method to handle JavaScript changes to the value of window.status. The following example traces the status value:
override public function updateStatus(status:String):void { trace(status); }
The requested status is passed as a string to the updateStatus() method.
The HTMLLoader object does not provide a status bar.

Handling changes of the window.document.title property

Adobe AIR 1.0 and later
override the updateTitle() method to handle JavaScript changes to the value of window.document.title. The following example changes the window title and appends the string, "Sample," to the title:
override public function updateTitle(title:String):void { htmlLoader.stage.nativeWindow.title = title + " - Sample"; }
When document.title is set on an HTML page, the requested title is passed as a string to the updateTitle() method.
Changes to document.title do not have to change the title of the window containing the HTMLLoader object. You could, for example, change another interface element, such as a text field.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Scripting the AIR HTML Container

Handling JavaScript calls to window.blur() and window.focus()

Adobe AIR 1.0 and later
Override the windowBlur() and windowFocus() methods to handle JavaScript calls to window.blur() and
window.focus(), as shown in the following example:
override public function windowBlur():void { htmlLoader.alpha = 0.5; } override public function windowFocus():void { htmlLoader.alpha = 1.0; NativeApplication.nativeApplication.activate(htmlLoader.stage.nativeWindow); }
Note: AIR does not provide an API for deactivating a window or application.

Creating windows with scrolling HTML content

Adobe AIR 1.0 and later
63
The HTMLLoader class includes a static method, HTMLLoader.createRootWindow(), which lets you open a new window (represented by a NativeWindow object) that contains an HTMLLoader object and define some user interface settings for that window. The method takes four parameters, which let you define the user interface:
Parameter Description
visible A Boolean value that specifies whether the window is initially visible (true) or not (false).
windowInitOptions A NativeWindowInitOptions object. The NativeWindowInitOptions class defines initialization options for a
scrollBarsVisible Whether there are scroll bars (true) or not (false).
bounds A Rectangle object defining the position and size of the new window.
NativeWindow object, including the following: whether the window is minimizable, maximizable, or resizable, whether the window has system chrome or custom chrome, whether the window is transparent or not (for windows that do not use system chrome), and the type of window.
For example, the following code uses the HTMLLoader.createRootWindow() method to create a window with HTMLLoader content that uses scroll bars:
var initOptions = new air.NativeWindowInitOptions(); var bounds = new air.Rectangle(10, 10, 600, 400); var html2 = air.HTMLLoader.createRootWindow(true, initOptions, true, bounds); var urlReq2 = new air.URLRequest("http://www.example.com"); html2.load(urlReq2); html2.stage.nativeWindow.activate();
Note: Windows created by calling createRootWindow() directly in JavaScript remain independent from the opening HTML window. The JavaScript Window
createRootWindow() indirectly by overriding the HTMLHost createWindow() method to call createRootWindow(), then opener and parent do reference the opening HTML window.
opener and parent properties, for example, are null. However, if you call
Last updated 9/28/2011

Chapter 5: Working with vectors

Adobe AIR 1.5 and later
A Vector instance is a typed array, which means that all the elements in a Vector instance always have the same data type. Some AIR APIs, such as NativeProcess and NetworkInfo, use Vectors as data types for properties or methods.
In JavaScript code running in Adobe AIR, the Vector class is referenced as air.Vector (in the AIRAliases.js file).

Basics of vectors

Adobe AIR 1.5 and later
When you declare a Vector variable or instantiate a Vector object, you explicitly specify the data type of the objects that the Vector can contain. The specified data type is known as the Vector’s base type. At run time, any code that sets or retrieves a value of a Vector is checked. If the data type of the object being added or retrieved doesn’t match the Vector’s base type, an error occurs.
64
In addition to the data type restriction, the Vector class has other restrictions that distinguish it from the Array class:
A Vector is a dense array. An Array object may have values in indices 0 and 7 even if it has no values in positions 1
through 6. However, a Vector must have a value (or
A Vector can optionally be fixed length. This means that the number of elements the Vector contains can’t change.
Access to a Vector’s elements is bounds-checked. You can never read a value from an index greater than the final
element ( other words, you can only set a value at an existing index or at index
As a result of its restrictions, a Vector has three primary benefits over an Array instance whose elements are all instances of a single class:
Performance: array element access and iteration are much faster when using a Vector instance than when using an
Array instance.
Type safety: examples of such errors include assigning a value of the incorrect data type to a Vector or expecting
the wrong data type when reading a value from a Vector. At run time, data types are checked when adding data to or reading data from a Vector object.
Reliability: run-time range checking (or fixed-length checking) increases reliability significantly over Arrays.
Aside from the additional restrictions and benefits, the Vector class is very much like the Array class. The properties and methods of a Vector object are similar—usually identical—to the properties and methods of an Array. In most situations where you would use an Array in which all the elements have the same data type, a Vector instance is preferable.
length - 1). You can never set a value with an index more than one beyond the current final index. (In
null) in each index.
[length].)
Important concepts and terms
The following reference list contains important terms to know when programming array and vector handling routines:
Array access ([]) operator A pair of square brackets surrounding an index or key that uniquely identifies an array
element. This syntax is used after a vector variable name to specify a single element of the vector rather than the entire vector.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with vectors
Base type The data type of the objects that a Vector instance is allowed to store.
Element A single item in a vector.
Index The numeric “address” used to identify a single element in an indexed array.
T The standard convention that’s used in this documentation to represent the base type of a Vector instance, whatever
that base type happens to be. The T convention is used to represent a class name, as shown in the Type parameter description. (“T” stands for “type,” as in “data type.”).
Type parameter The syntax that’s used with the Vector class name to specify the Vector’s base type (the data type of
the objects that it stores). The syntax consists of a period (
<>). Put together, it looks like this: Vector.<T>. In this documentation, the class specified in the type parameter is
( represented generically as
Vector A type of array whose elements are all instances of the same data type.
T.
.), then the data type name surrounded by angle brackets

Creating vectors

AIR 1.5 and later
65
You create a Vector instance by calling the air.Vector["<T>"]() constructor. When you call this constructor, you specify the base type of the Vector variable. You specify the Vector’s base type using type parameter syntax. The type parameter immediately follows the word base class name surrounded by angle brackets (
var v = new air.Vector["<String>"]();
Vector in the code. It consists of a left bracket, then a string containing the
<>), followed by a right bracket. This example shows this syntax:
In this example, the variable v is declared as a vector of String objects. In other words, it represents an indexed array that can only hold String instances.
If you use the air.Vector["<T>"]() constructor without any arguments, it creates an empty Vector instance. You can test that a Vector is empty by checking its
Vector["<T>"]() constructor with no arguments:
var names = new air.Vector["<String>"](); air. trace(names.length); // output: 0
length property. For example, the following code calls the
If you know ahead of time how many elements a Vector initially needs, you can pre-define the number of elements in the Vector. To create a Vector with a certain number of elements, pass the number of elements as the first parameter
length parameter). Because Vector elements can’t be empty, the elements are filled with instances of the base
(the type. If the base type is a reference type that allows all contain the default value for the class. For example, a Number variable can’t be code listing the Vector named
var ages = new air.Vector["<Number>"](3); air.trace(ages); // output: NaN, NaN, NaN
ages is created with three elements, each containing the default Number value NaN:
null values, the elements all contain null. Otherwise, the elements
null. Consequently, in the following
Using the Vector["<T>"]() constructor you can also create a fixed-length Vector by passing true for the second parameter (the
fixed parameter). In that case the Vector is created with the specified number of elements and the
number of elements can’t be changed. Note, however, that you can still change the values of the elements of a fixed­length Vector.
If you create a Vector of AIR runtime objects (classes defined in the window.runtime object), reference the class’s fully qualified ActionScript 3.0 name when calling the Vector constructor. For example, the following code creates a Vector of File objects:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with vectors
var files = new air.Vector["flash.filesystem.File"](3);

Inserting elements into a vector

Adobe AIR 1.5 and later
The most basic way to add an element to vector is to use the array access ([]) operator:
songTitles[5] = "Happy Birthday";
If the Vector doesn’t already have an element at that index, the index is created and the value is stored there.
With a Vector object, you can only assign a value to an existing index or to the next available index. The next available index corresponds to the Vector object’s to use code like this listing:
myVector[myVector.length] = valueToAdd;
As with arrays, three of the Vector class methods—push(), unshift(), and splice()—allow you to insert elements into a vector.
Note: If a Vector object’s fixed property is true, the total number of elements in the Vector can’t change. If you try to add a new element to a fixed-length Vector using the
length property. The safest way to add a new element to a Vector object is
push() method or other means, an error occurs.
66

Retrieving values and removing vector elements

Adobe AIR 1.5 and later
The simplest way to retrieve the value of an element from vector is to use the array access ([]) operator. To retrieve the value of an vector element, use the vector object name and index number on the right side of an assignment statement:
var myFavoriteSong = songTitles[3];
It’s possible to attempt to retrieve a value from a vector using an index where no element exists. In that case, a Vector throws a RangeError exception.
Three methods of the Array and Vector classes—pop(), shift(), and splice()—allow you to remove elements.
var vegetables = new air.Vector["<String>"]; vegetables.push("spinach"); vegetables.push("green pepper"); vegetables.push("cilantro"); vegetables.push("onion"); var spliced = vegetables.splice(2, 2); air.trace(spliced); // output: spinach,green pepper
You can truncate a vector using thelength property.
If you set the length property of a vector to a length that is less than the current length of the vector, the vector is truncated. Any elements stored at index numbers higher than the new value of
length minus 1 are removed.
Note: If a Vector object’s fixed property is true, the total number of elements in the Vector can’t change. If you try to remove an element from or truncate a fixed-length Vector using the techniques described here, an error occurs.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with vectors

Properties and methods of Vector objects

Adobe AIR 1.5 and later
Many of the same methods and properties of Array objects are available for vector object. For example, you can call
reverse() method to change the order of elements of a Vector. You can call the sort() method to sort the
the elements of a Vector. However, the Vector class does not include a
For details on supported properties and methods, see the Vector class documentation in the Adobe AIR Language Reference for HTML Developers.
sortOn() method.

Example: Using AIR APIs that require vectors

Adobe AIR 1.5 and later
Some Adobe AIR runtime classes use vectors as properties or method return values. For example, the
findInterfaces() method of the NetworkInfo class returns an array of NetworkInterface objects. The arguments
property NativeProcessStartupInfo class is a vector of strings.
67

Accessing AIR APIs that return vector objects

Adobe AIR 2.0 and later
The findInterfaces() method of the NetworkInfo class returns an array of NetworkInterface objects. For example, the following code lists the computer’s network interfaces:
var netInfo = air.NetworkInfo; var interfaces = netInfo.findInterfaces(); for (i = 0; i < interfaces.length; i++) {
air.trace(interfaces[i].name]; air.trace(" hardware address: ", interface.hardwareAddress);
}
You iterate through the vector of NetworkInfo objects just as you would iterate through an array. You use a for loop and use square brackets to access indexed elements of the vector.
The interfaces property of the NetworkInterface object is a vector of InterfaceAddress objects. The following code extends the previous example, adding a function to enumerate interface addresses for each network interface:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with vectors
var netInfo = air.NetworkInfo; var interfaces = netInfo.findInterfaces(); for (i = 0; i < interfaces.length; i++) {
air.trace(interfaces[i].name]; air.trace(" hardware address: ", interface.hardwareAddress); air.trace(" addresses: ", traceAddresses(i);
}
function traceAddresses(i) {
returnString = new String(); for (j = 0; j < interfaces[i].addresses.length; j++)
returnString += interfaces[i],addresses[j].address + " ";
}
}

Setting AIR APIs that are vectors

Adobe AIR 2.0 and later
The arguments property NativeProcessStartupInfo class is a vector of strings. To set this property, create a vector of strings using the
air.Vector() constructor. You can use the push() method to add strings to the vector:
68
var arguments = new air.Vector["<String>"]();
arguments.push("test"); arguments.push("44");
var startupInfo = new air.NativeProcessStartupInfo(); startupInfo.arguments = arguments; startupInfo.executable = File.applicationDirectory.resolvePath("myApplication.exe");
process = new air.NativeProcess(); process.start(startupInfo);
For more information on using the native process API, see “Communicating with Native Processes” in Networking and communication.
Last updated 9/28/2011

Chapter 6: AIR security

Adobe AIR 1.0 and later

AIR security basics

Adobe AIR 1.0 and later
AIR applications run with the same security restrictions as native applications. In general, AIR applications, like native applications, have broad access to operating system capabilities such as reading and writing files, starting applications, drawing to the screen, and communicating with the network. Operating system restrictions that apply to native applications, such as user-specific privileges, equally apply to AIR applications.
Although the Adobe® AIR® security model is an evolution of the Adobe® Flash® Player security model, the security contract is different from the security contract applied to content in a browser. This contract offers developers a secure means of broader functionality for rich experiences with freedoms that would be inappropriate for a browser-based application.
69
AIR applications are written using either compiled bytecode (SWF content) or interpreted script (JavaScript, HTML) so that the runtime provides memory management. This minimizes the chances of AIR applications being affected by vulnerabilities related to memory management, such as buffer overflows and memory corruption. These are some of the most common vulnerabilities affecting desktop applications written in native code.

Installation and updates

Adobe AIR 1.0 and later
AIR applications are distributed via AIR installer files which use the air extension or via native installers, which use the file format and extension of the native platform. For example, the native installer format of Windows is an EXE file, and for Android the native format is an APK file.
When Adobe AIR is installed and an AIR installer file is opened, the AIR runtime administers the installation process. When a native installer is used, the operating system administers the installation process.
Note: Developers can specify a version, and application name, and a publisher source, but the initial application installation workflow itself cannot be modified. This restriction is advantageous for users because all AIR applications share a secure, streamlined, and consistent installation procedure administered by the runtime. If application customization is necessary, it can be provided when the application is first executed.

Runtime installation location

Adobe AIR 1.0 and later
AIR applications first require the runtime to be installed on a user's computer, just as SWF files first require the Flash Player browser plug-in to be installed.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
The runtime is installed to the following location on desktop computers:
Mac OS: /Library/Frameworks/
Windows: C:\Program Files\Common Files\Adobe AIR
Linux: /opt/Adobe AIR/
On Mac OS, to install an updated version of an application, the user must have adequate system privileges to install to the application directory. On Windows and Linux, a user must have administrative privileges.
Note: On iOS, the AIR runtime is not installed separately; every AIR app is a self-contained application.
The runtime can be installed in two ways: using the seamless install feature (installing directly from a web browser) or via a manual install.

Seamless install (runtime and application)

Adobe AIR 1.0 and later
The seamless install feature provides developers with a streamlined installation experience for users who do not have Adobe AIR installed yet. In the seamless install method, the developer creates a SWF file that presents the application for installation. When a user clicks in the SWF file to install the application, the SWF file attempts to detect the runtime. If the runtime cannot be detected it is installed, and the runtime is activated immediately with the installation process for the developer's application.
70

Manual install

Adobe AIR 1.0 and later
Alternatively, the user can manually download and install the runtime before opening an AIR file. The developer can then distribute an AIR file by different means (for instance, via e-mail or an HTML link on a website). When the AIR file is opened, the runtime begins to process the application installation.

Application installation flow

Adobe AIR 1.0 and later
The AIR security model allows users to decide whether to install an AIR application. The AIR install experience provides several improvements over native application install technologies that make this trust decision easier for users:
The runtime provides a consistent installation experience on all operating systems, even when an AIR application
is installed from a link in a web browser. Most native application install experiences depend upon the browser or other application to provide security information, if it is provided at all.
The AIR application install experience identifies the source of the application and information about what
privileges are available to the application (if the user allows the installation to proceed).
The runtime administers the installation process of an AIR application. An AIR application cannot manipulate the
installation process the runtime uses.
In general, users should not install any desktop application that comes from a source that they do not trust, or that cannot be verified. The burden of proof on security for native applications is equally true for AIR applications as it is for other installable applications.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security

Application destination

Adobe AIR 1.0 and later
The installation directory can be set using one of the following two options:
1 The user customizes the destination during installation. The application installs to wherever the user specifies.
2 If the user does not change the install destination, the application installs to the default path as determined by the
runtime:
Mac OS: ~/Applications/
Windows XP and earlier: C:\Program Files\
Windows Vista: ~/Apps/
Linux: /opt/
If the developer specifies an installFolder setting in the application descriptor file, the application is installed to a subpath of this directory.

The AIR file system

Adobe AIR 1.0 and later
71
The install process for AIR applications copies all files that the developer has included within the AIR installer file onto the user's local computer. The installed application is composed of:
Windows: A directory containing all files included in the AIR installer file. The runtime also creates an exe file
during the installation of the AIR application.
Linux: A directory containing all files included in the AIR installer file. The runtime also creates a bin file during
the installation of the AIR application.
Mac OS: An app file that contains all of the contents of the AIR installer file. It can be inspected using the "Show
Package Contents" option in Finder. The runtime creates this app file as part of the installation of the AIR application.
An AIR application is run by:
Windows: Running the .exe file in the install folder, or a shortcut that corresponds to this file (such as a shortcut
on the Start Menu or desktop).
Linux: Launching the .bin file in the install folder, choosing the application from the Applications menu, or running
from an alias or desktop shortcut.
Mac OS: Running the .app file or an alias that points to it.
The application file system also includes subdirectories related to the function of the application. For example, information written to encrypted local storage is saved to a subdirectory in a directory named after the application identifier of the application.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security

AIR application storage

Adobe AIR 1.0 and later
AIR applications have privileges to write to any location on the user's hard drive; however, developers are encouraged to use the application are located in a standard location depending on the user's operating system:
app-storage:/ path for local storage related to their application. Files written to app-storage:/ from an
On Mac OS: the storage directory of an application is <appData>/<appId>/Local Store/ where <appData> is
the user's “preferences folder,” typically:
/Users/<user>/Library/Preferences
On Windows: the storage directory of an application is <appData>\<appId>\Local Store\ where <appData> is the
user's CSIDL_APPDATA “Special Folder,” typically:
C:\Documents and Settings\<user>\Application Data
On Linux: <appData>/<appID>/Local Store/where <appData> is /home/<user>/.appdata
You can access the application storage directory via the air.File.applicationStorageDirectory property. You can access its contents using the
system” on page 145.
resolvePath() method of the File class. For details, see “Working with the file

Updating Adobe AIR

Adobe AIR 1.0 and later
72
When the user installs an AIR application that requires an updated version of the runtime, the runtime automatically installs the required runtime update.
To update the runtime, a user must have administrative privileges for the computer.

Updating AIR applications

Adobe AIR 1.0 and later
Development and deployment of software updates are one of the biggest security challenges facing native code applications. The AIR API provides a mechanism to improve this: the upon launch to check a remote location for an AIR file. If an update is appropriate, the AIR file is downloaded, installed, and the application restarts. Developers can use this class not only to provide new functionality but also respond to potential security vulnerabilities.
The Updater class can only be used to update applications distributed as AIR files. Applications distributed as native applications must use the update facilities, if any, of the native operating system.
Note: Developers can specify the version of an application by setting the versionNumber property of the application descriptor file.
Updater.update() method can be invoked

Uninstalling an AIR application

Adobe AIR 1.0 and later
Removing an AIR application removes all files in the application directory. However, it does not remove all files that the application may have written to outside of the application directory. Removing AIR applications does not revert changes the AIR application has made to files outside of the application directory.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security

Windows registry settings for administrators

Adobe AIR 1.0 and later
On Windows, administrators can configure a machine to prevent (or allow) AIR application installation and runtime updates. These settings are contained in the Windows registry under the following key: HKLM\Software\Policies\Adobe\AIR. They include the following:
Registry setting Description
73
AppInstallDisabled Specifies that AIR application installation and uninstallation are allowed. Set to 0 for “allowed,” set to 1
UntrustedAppInstallDisabled Specifies that installation of untrusted AIR applications (applications that do not includes a trusted
UpdateDisabled Specifies that updating the runtime is allowed, either as a background task or as part of an explicit
for “disallowed.”
certificate) is allowed. Set to 0 for “allowed,” set to 1 for “disallowed.”
installation. Set to 0 for “allowed,” set to 1 for “disallowed.”

HTML security in Adobe AIR

Adobe AIR 1.0 and later
This topic describes the AIR HTML security architecture and how to use iframes, frames, and the sandbox bridge to set up HTML-based applications and safely integrate HTML content into SWF-based applications.
The runtime enforces rules and provides mechanisms for overcoming possible security vulnerabilities in HTML and JavaScript. The same rules are enforced whether your application is primarily written in JavaScript or whether you load the HTML and JavaScript content into a SWF-based application. Content in the application sandbox and the non­application security sandbox have different privileges. When loading content into an iframe or frame, the runtime provides a secure sandbox bridge mechanism that allows content in the frame or iframe to communicate securely with content in the application security sandbox.
The AIR SDK provides three classes for rendering HTML content.
The HTMLLoader class provides close integration between JavaScript code and the AIR APIs.
The StageWebView class is an HTML rendering class and has very limited integration with the host AIR application. Content loaded by the StageWebView class is never placed in the application security sandbox and cannot access data or call functions in the host AIR application. On desktop platforms, the StageWebView class uses the built-in AIR HTML engine, based on Webkit, which is also used by the HTMLLoader class. On mobile platforms, the StageWebView class uses the HTML control provided by the operating system. Thus, on mobile platforms the StageWebView class has the same security considerations and vulnerabilities as the system web browser.
The TextField class can display strings of HTML text. No JavaScript can be executed, but the text can include links and externally loaded images.
For more information, see “Avoiding security-related JavaScript errors” on page 22.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security

Overview on configuring your HTML-based application

Adobe AIR 1.0 and later
Frames and iframes provide a convenient structure for organizing HTML content in AIR. Frames provide a means both for maintaining data persistence and for working securely with remote content.
Because HTML in AIR retains its normal, page-based organization, the HTML environment completely refreshes if the top frame of your HTML content “navigates” to a different page. You can use frames and iframes to maintain data persistence in AIR, much the same as you would for a web application running in a browser. Define your main application objects in the top frame and they persist as long as you don’t allow the frame to navigate to a new page. Use child frames or iframes to load and display the transient parts of the application. (There are a variety of ways to maintain data persistence that can be used in addition to, or instead of, frames. These include cookies, local shared objects, local file storage, the encrypted file store, and local database storage.)
Because HTML in AIR retains its normal, blurred line between executable code and data, AIR puts content in the top frame of the HTML environment into the application sandbox. After the page operations, such as
eval(), that can convert a string of text into an executable object. This restriction is enforced even
when an application does not load remote content. To allow HTML content to execute these restricted operations, you must use frames or iframes to place the content into a non-application sandbox. (Running content in a sandboxed child frame may be necessary when using some JavaScript application frameworks that rely on the For a complete list of the restrictions on JavaScript in the application sandbox, see
different sandboxes” on page 76.
load event, AIR restricts any
eval() function.)
Code restrictions for content in
74
Because HTML in AIR retains its ability to load remote, possibly insecure content, AIR enforces a same-origin policy that prevents content in one domain from interacting with content in another. To allow interaction between application content and content in another domain, you can set up a bridge to serve as the interface between a parent and a child frame.
Setting up a parent-child sandbox relationship
Adobe AIR 1.0 and later
AIR adds the sandboxRoot and documentRoot attributes to the HTML frame and iframe elements. These attributes let you treat application content as if it came from another domain:
Attribute Description
sandboxRoot The URL to use for determining the sandbox and domain in which to place the
frame content. The
documentRoot The URL from which to load the frame content. The file:, app:, or app-
storage:
The following example maps content installed in the sandbox subdirectory of the application to run in the remote sandbox and the www.example.com domain:
<iframe src="ui.html" sandboxRoot="http://www.example.com/local/" documentRoot="app:/sandbox/"> </iframe>
file:, http:, or https: URL schemes must be used.
URL schemes must be used.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
Setting up a bridge between parent and child frames in different sandboxes or domains
Adobe AIR 1.0 and later
AIR adds the childSandboxBridge and parentSandboxBridge properties to the window object of any child frame. These properties let you define bridges to serve as interfaces between a parent and a child frame. Each bridge goes in one direction:
childSandboxBridge — The childSandboxBridge property allows the child frame to expose an interface to content
in the parent frame. To expose an interface, you set the frame. You can then access the object or function from content in the parent frame. The following example shows how a script running in a child frame can expose an object containing a function and a property to its parent:
var interface = {}; interface.calculatePrice = function(){ return .45 + 1.20; } interface.storeID = "abc" window.childSandboxBridge = interface;
If this child content is in an iframe assigned an id of "child", you can access the interface from parent content by reading the
childSandboxBridge property of the frame:
childSandbox property to a function or object in the child
75
var childInterface = document.getElementById("child").childSandboxBridge; air.trace(childInterface.calculatePrice()); //traces "1.65" air.trace(childInterface.storeID)); //traces "abc"
parentSandboxBridge — The parentSandboxBridge property allows the parent frame to expose an interface to
content in the child frame. To expose an interface, you set the
parentSandbox property of the child frame to a function
or object in the parent frame. You can then access the object or function from content in the child frame. The following example shows how a script running in the parent frame can expose an object containing a save function to a child:
var interface = {}; interface.save = function(text){ var saveFile = air.File("app-storage:/save.txt"); //write text to file } document.getElementById("child").parentSandboxBridge = interface;
Using this interface, content in the child frame could save text to a file named save.txt. However, it would not have any other access to the file system. In general, application content should expose the narrowest possible interface to other sandboxes. The child content could call the save function as follows:
var textToSave = "A string."; window.parentSandboxBridge.save(textToSave);
If child content attempts to set a property of the parentSandboxBridge object, the runtime throws a SecurityError exception. If parent content attempts to set a property of the
childSandboxBridge object, the runtime throws a
SecurityError exception.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security

Code restrictions for content in different sandboxes

Adobe AIR 1.0 and later
As discussed in the introduction to this topic, “HTML security in Adobe AIR” on page 73, the runtime enforces rules and provides mechanisms for overcoming possible security vulnerabilities in HTML and JavaScript. This topic lists those restrictions. If code attempts to call these restricted APIs, the runtime throws an error with the message “Adobe AIR runtime security violation for JavaScript code in the application security sandbox.”
For more information, see “Avoiding security-related JavaScript errors” on page 22.
Restrictions on using the JavaScript eval() function and similar techniques
Adobe AIR 1.0 and later
For HTML content in the application security sandbox, there are limitations on using APIs that can dynamically transform strings into executable code after the code is loaded (after the dispatched and the
onload handler function has finished executing). This is to prevent the application from
inadvertently injecting (and executing) code from non-application sources (such as potentially insecure network domains).
For example, if your application uses string data from a remote source to write to the innerHTML property of a DOM element, the string could include executable (JavaScript) code that could perform insecure operations. However, while the content is loading, there is no risk of inserting remote strings into the DOM.
onload event of the body element has been
76
One restriction is in the use of the JavaScript eval() function. Once code in the application sandbox is loaded and after processing of the onload event handler, you can only use the apply to the use of the
eval() function after code is loaded from the application security sandbox:
eval() function in limited ways. The following rules
Expressions involving literals are allowed. For example:
eval("null"); eval("3 + .14"); eval("'foo'");
Object literals are allowed, as in the following:
{ prop1: val1, prop2: val2 }
Object literal setter/getters are prohibited, as in the following:
{ get prop1() { ... }, set prop1(v) { ... } }
Array literals are allowed, as in the following:
[ val1, val2, val3 ]
Expressions involving property reads are prohibited, as in the following:
a.b.c
Function invocation is prohibited.
Function definitions are prohibited.
Setting any property is prohibited.
Function literals are prohibited.
However, while the code is loading, before the onload event, and during execution the onload event handler function, these restrictions do not apply to content in the application security sandbox.
For example, after code is loaded, the following code results in the runtime throwing an exception:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
eval("alert(44)"); eval("myFunction(44)"); eval("NativeApplication.applicationID");
Dynamically generated code, such as that which is made when calling the eval() function, would pose a security risk if allowed within the application sandbox. For example, an application may inadvertently execute a string loaded from a network domain, and that string may contain malicious code. For example, this could be code to delete or alter files on the user’s computer. Or it could be code that reports back the contents of a local file to an untrusted network domain.
Ways to generate dynamic code are the following:
Calling the eval() function.
Using innerHTML properties or DOM functions to insert script tags that load a script outside of the application
directory.
Using innerHTML properties or DOM functions to insert script tags that have inline code (rather than loading a
script via the
src attribute).
Setting the src attribute for a script tags to load a JavaScript file that is outside of the application directory.
Using the javascript URL scheme (as in href="javascript:alert('Test')").
Using the setInterval() or setTimout()function where the first parameter (defining the function to run
asynchronously) is a string (to be evaluated) rather than a function name (as in
setTimeout('x = 4', 1000)).
Calling document.write() or document.writeln().
Code in the application security sandbox can only use these methods while content is loading.
77
These restrictions do not prevent using eval() with JSON object literals. This lets your application content work with the JSON JavaScript library. However, you are restricted from using overloaded JSON code (with event handlers).
For other Ajax frameworks and JavaScript code libraries, check to see if the code in the framework or library works within these restrictions on dynamically generated code. If they do not, include any content that uses the framework or library in a non-application security sandbox. For details, see Restrictions for JavaScript inside AIR and
Scripting
between application and non-application content” on page 81. Adobe maintains a list of Ajax frameworks known to
support the application security sandbox, at http://www.adobe.com/products/air/develop/ajax/features/.
Unlike content in the application security sandbox, JavaScript content in a non-application security sandbox can call
eval() function to execute dynamically generated code at any time.
the
Restrictions on access to AIR APIs (for non-application sandboxes)
Adobe AIR 1.0 and later
JavaScript code in a non-application sandbox does not have access to the window.runtime object, and as such this code cannot execute AIR APIs. If content in a non-application security sandbox calls the following code, the application throws a TypeError exception:
try { window.runtime.flash.system.NativeApplication.nativeApplication.exit(); } catch (e) { alert(e); }
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
The exception type is TypeError (undefined value), because content in the non-application sandbox does not recognize the
window.runtime object, so it is seen as an undefined value.
You can expose runtime functionality to content in a non-application sandbox by using a script bridge. For details, see
Scripting between application and non-application content” on page 81.
and
Restrictions on using XMLHttpRequest calls
Adobe AIR 1.0 and later
HTML content in the application security sandbox cannot use synchronous XMLHttpRequest methods to load data from outside of the application sandbox while the HTML content is loading and during
By default, HTML content in non-application security sandboxes are not allowed to use the JavaScript XMLHttpRequest object to load data from domains other than the domain calling the request. A can include an
allowcrosscomainxhr attribute. Setting this attribute to any non-null value allows the content in the
frame or iframe to use the JavaScript XMLHttpRequest object to load data from domains other than the domain of the code calling the request:
<iframe id="UI" src="http://example.com/ui.html" sandboxRoot="http://example.com/" allowcrossDomainxhr="true" documentRoot="app:/"> </iframe>
onLoad event.
frame or iframe tag
78
For more information, see “Scripting between content in different domains” on page 79.
Restrictions on loading CSS, frame, iframe, and img elements (for content in non-application sandboxes)
Adobe AIR 1.0 and later
HTML content in remote (network) security sandboxes can only load CSS, frame, iframe, and img content from remote sandboxes (from network URLs).
HTML content in local-with-filesystem, local-with-networking, or local-trusted sandboxes can only load CSS, frame, iframe, and
img content from local sandboxes (not from application or remote sandboxes).
Restrictions on calling the JavaScript window.open() method
Adobe AIR 1.0 and later
If a window that is created via a call to the JavaScript window.open() method displays content from a non-application security sandbox, the window’s title begins with the title of the main (launching) window, followed by a colon character. You cannot use code to move that portion of the title of the window off screen.
Content in non-application security sandboxes can only successfully call the JavaScript window.open() method in response to an event triggered by a user mouse or keyboard interaction. This prevents non-application content from creating windows that might be used deceptively (for example, for phishing attacks). Also, the event handler for the mouse or keyboard event cannot set the
setTimeout() function).
window.open() method to execute after a delay (for example by calling the
Content in remote (network) sandboxes can only use the window.open() method to open content in remote network sandboxes. It cannot use the
window.open() method to open content from the application or local sandboxes.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
Content in the local-with-filesystem, local-with-networking, or local-trusted sandboxes (see Security sandboxes) can only use the content from the application or remote sandboxes.
window.open() method to open content in local sandboxes. It cannot use window.open()to open
Errors when calling restricted code
Adobe AIR 1.0 and later
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."
For more information, see “Avoiding security-related JavaScript errors” on page 22.

Sandbox protection when loading HTML content from a string

Adobe AIR 1.0 and later
The loadString() method of the HTMLLoader class lets you create HTML content at run time. However, data that you use as the HTML content can be corrupted if the data is loaded from an insecure Internet source. For this reason, by default, HTML created using the access to AIR APIs. However, you can set the HTMLLoader object to true to place HTML created using the For more information, see Loading HTML content from a string.
loadString() method is not placed in the application sandbox and it has no
placeLoadStringContentInApplicationSandbox property of an
loadString() method into the application sandbox.
79

Scripting between content in different domains

Adobe AIR 1.0 and later
AIR applications are granted special privileges when they are installed. It is crucial that the same privileges not be leaked to other content, including remote files and local files that are not part of the application.

About the AIR sandbox bridge

Adobe AIR 1.0 and later
Normally, content from other domains cannot call scripts in other domains.
There are still cases where the main AIR application requires content from a remote domain to have controlled access to scripts in the main AIR application, or vice versa. To accomplish this, the runtime provides a sandbox bridge mechanism, which serves as a gateway between the two sandboxes. A sandbox bridge can provide explicit interaction between remote and application security sandboxes.
The sandbox bridge exposes two objects that both loaded and loading scripts can access:
The parentSandboxBridge object lets loading content expose properties and functions to scripts in the loaded
content.
The childSandboxBridge object lets loaded content expose properties and function to scripts in the loading
content.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
Objects exposed via the sandbox bridge are passed by value, not by reference. All data is serialized. This means that the objects exposed by one side of the bridge cannot be set by the other side, and that objects exposed are all untyped. Also, you can only expose simple objects and functions; you cannot expose complex objects.
If child content attempts to set a property of the parentSandboxBridge object, the runtime throws a SecurityError exception. Similarly, if parent content attempts to set a property of the childSandboxBridge object, the runtime throws a SecurityError exception.

Sandbox bridge example (HTML)

Adobe AIR 1.0 and later
In HTML content, the parentSandboxBridge and childSandboxBridge properties are added to the JavaScript window object of a child document. For an example of how to set up bridge functions in HTML content, see
up a sandbox bridge interface” on page 36.
Setting

Limiting API exposure

Adobe AIR 1.0 and later
80
When exposing sandbox bridges, it's important to expose high-level APIs that limit the degree to which they can be abused. Keep in mind that the content calling your bridge implementation may be compromised (for example, via a code injection). So, for example, exposing a a bridge is vulnerable to abuse. It would be better to expose a path and reads a specific file. The more semantic approach limits the damage that an application can do once part of it is compromised.
readFile(path) method (that reads the contents of an arbitrary file) via
readApplicationSetting() API that doesn't take a
More Help topics
Cross-scripting content in different security sandboxes” on page 34

Writing to disk

Adobe AIR 1.0 and later
Applications running in a web browser have only limited interaction with the user's local file system. Web browsers implement security policies that ensure that a user's computer cannot be compromised as a result of loading web content. For example, SWF files running through Flash Player in a browser cannot directly interact with files already on a user's computer. Shared objects and cookies can be written to a user's computer for the purpose of maintaining user preferences and other data, but this is the limit of file system interaction. Because AIR applications are natively installed, they have a different security contract, one which includes the capability to read and write across the local file system.
This freedom comes with high responsibility for developers. Accidental application insecurities jeopardize not only the functionality of the application, but also the integrity of the user's computer. For this reason, developers should
Best security practices for developers” on page 82.
read
AIR developers can access and write files to the local file system using several URL scheme conventions:
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
URL scheme Description
81
app:/ An alias to the application directory. Files accessed from this path are assigned the application sandbox and have
app-storage:/ An alias to the local storage directory, standardized by the runtime. Files accessed from this path are assigned a
file:/// An alias that represents the root of the user's hard disk. A file accessed from this path is assigned an application
the full privileges granted by the runtime.
non-application sandbox.
sandbox if the file exists in the application directory, and a non-application sandbox otherwise.
Note: AIR applications cannot modify content using the app: URL scheme. Also, the application directory may be read only because of administrator settings.
Unless there are administrator restrictions to the user's computer, AIR applications are privileged to write to any location on the user's hard drive. Developers are advised to use the their application. Files written to
app-storage:/ from an application are put in a standard location:
app-storage:/ path for local storage related to
On Mac OS: the storage directory of an application is <appData>/<appId>/Local Store/ where <appData> is
the user's preferences folder. This is typically
/Users/<user>/Library/Preferences
On Windows: the storage directory of an application is <appData>\<appId>\Local Store\ where <appData> is
the user's CSIDL_APPDATA Special Folder. This is typically
Settings\<userName>\Application Data
C:\Documents and
On Linux: <appData>/<appID>/Local Store/where <appData> is /home/<user>/.appdata
If an application is designed to interact with existing files in the user's file system, be sure to read “Best security
practices for developers” on page 82.

Working securely with untrusted content

Adobe AIR 1.0 and later
Content not assigned to the application sandbox can provide additional scripting functionality to your application, but only if it meets the security criteria of the runtime. This topic explains the AIR security contract with non-application content.

Scripting between application and non-application content

Adobe AIR 1.0 and later
AIR applications that script between application and non-application content have more complex security arrangements. Files that are not in the application sandbox are only allowed to access the properties and methods of files in the application sandbox through the use of a sandbox bridge. A sandbox bridge acts as a gateway between application content and non-application content, providing explicit interaction between the two files. When used correctly, sandbox bridges provide an extra layer of security, restricting non-application content from accessing object references that are part of application content.
The benefit of sandbox bridges is best illustrated through example. Suppose an AIR music store application wants to provide an API to advertisers who want to create their own SWF files, with which the store application can then communicate. The store wants to provide advertisers with methods to look up artists and CDs from the store, but also wants to isolate some methods and properties from the third-party SWF file for security reasons.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security
A sandbox bridge can provide this functionality. By default, content loaded externally into an AIR application at runtime does not have access to any methods or properties in the main application. With a custom sandbox bridge implementation, a developer can provide services to the remote content without exposing these methods or properties. Consider the sandbox bridge as a pathway between trusted and untrusted content, providing communication between loader and loadee content without exposing object references.
For more information on how to securely use sandbox bridges, see “Scripting between content in different domains” on page 79.

Best security practices for developers

Adobe AIR 1.0 and later
Although AIR applications are built using web technologies, it is important for developers to note that they are not working within the browser security sandbox. This means that it is possible to build AIR applications that can do harm to the local system, either intentionally or unintentionally. AIR attempts to minimize this risk, but there are still ways where vulnerabilities can be introduced. This topic covers important potential insecurities.
82

Risk from importing files into the application security sandbox

Adobe AIR 1.0 and later
Files that exist in the application directory are assigned to the application sandbox and have the full privileges of the runtime. Applications that write to the local file system are advised to write to separately from the application files on the user's computer, hence the files are not assigned to the application sandbox and present a reduced security risk. Developers are advised to consider the following:
app-storage:/. This directory exists
Include a file in an AIR file (in the installed application) only if it is necessary.
Include a scripting file in an AIR file (in the installed application) only if its behavior is fully understood and trusted.
Do not write to or modify content in the application directory. The runtime prevents applications from writing or
modifying files and directories using the
app:/ URL scheme by throwing a SecurityError exception.
Do not use data from a network source as parameters to methods of the AIR API that may lead to code execution.
This includes use of the
Loader.loadBytes() method and the JavaScript eval() function.

Risk from using an external source to determine paths

Adobe AIR 1.0 and later
An AIR application can be compromised when using external data or content. For this reason, take special care when using data from the network or file system. The onus of trust is ultimately on the developer and the network connections they make, but loading foreign data is inherently risky, and should not be used for input into sensitive operations. Developers are advised against the following:
Using data from a network source to determine a file name
Using data from a network source to construct a URL that the application uses to send private information
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
AIR security

Risk from using, storing, or transmitting insecure credentials

Adobe AIR 1.0 and later
Storing user credentials on the user's local file system inherently introduces the risk that these credentials may be compromised. Developers are advised to consider the following:
If credentials must be stored locally, encrypt the credentials when writing to the local file system. The runtime
provides an encrypted storage unique to each installed application, via the EncryptedLocalStore class. For details,
Encrypted local storage” on page 256.
see
Do not transmit unencrypted user credentials to a network source unless that source is trusted and the transmission
uses the HTTPS: or Transport Layer Security (TLS) protocols.
Never specify a default password in credential creation — let users create their own. Users who leave the default
unchanged expose their credentials to an attacker who already knows the default password.

Risk from a downgrade attack

Adobe AIR 1.0 and later
During application install, the runtime checks to ensure that a version of the application is not currently installed. If an application is already installed, the runtime compares the version string against the version that is being installed. If this string is different, the user can choose to upgrade their installation. The runtime does not guarantee that the newly installed version is newer than the older version, only that it is different. An attacker can distribute an older version to the user to circumvent a security weakness. For this reason, the developer is advised to make version checks when the application is run. It is a good idea to have applications check the network for required updates. That way, even if an attacker gets the user to run an old version, that old version will recognize that it needs to be updated. Also, using a clear versioning scheme for your application makes it more difficult to trick users into installing a downgraded version.
83

Code signing

Adobe AIR 1.0 and later
All AIR installer files are required to be code signed. Code signing is a cryptographic process of confirming that the specified origin of software is accurate. AIR applications can be signed using either by a certificate issued by an external certificate authority (CA) or by a self-signed certificate you create yourself. A commercial certificate from a well­known CA is strongly recommended and provides assurance to your users that they are installing your application, not a forgery. However, self-signed certificates can be created using Builder, or another application that uses assurance that the application being installed is genuine and should only be used for testing an application prior to public release.
adt for certificate generation. Self-signed certificates do not provide any
Last updated 9/28/2011
adt from the SDK or using either Flash, Flash

Chapter 7: Working with AIR native windows

Adobe AIR 1.0 and later
You use the classes provided by the Adobe® AIR® native window API to create and manage desktop windows.

Basics of native windows in AIR

Adobe AIR 1.0 and later
For quick explanations and code examples of working with native windows in AIR, see the following quick start articles on the Adobe Developer Connection:
Customizing the look and feel of a window
AIR provides an easy-to-use, cross-platform window API for creating native operating system windows using Flash®, Flex™, and HTML programming techniques.
84
With AIR, you have a wide latitude in developing the appearance of your application. The windows you create can look like a standard desktop application, matching Apple style when run on the Mac, conforming to Microsoft conventions when run on Windows, and harmonizing with the window manager on Linux—all without including a line of platform-specific code. Or you can use the skinnable, extensible chrome provided by the Flex framework to establish your own style no matter where your application is run. You can even draw your own window chrome with vector and bitmap artwork with full support for transparency and alpha blending against the desktop. Tired of rectangular windows? Draw a round one.

Windows in AIR

Adobe AIR 1.0 and later
AIR supports three distinct APIs for working with windows:
The ActionScript-oriented NativeWindow class provides the lowest level window API. Use NativeWindows in
ActionScript and Flash Professional-authored applications. Consider extending the NativeWindow class to specialize the windows used in your application.
In the HTML environment, you can use the JavaScript Window class, just as you would in a browser-based web
application. Calls to JavaScript Window methods are forwarded to the underlying native window object.
The Flex framework mx:WindowedApplication and mx:Window classes provide a Flex “wrapper” for the
NativeWindow class. The WindowedApplication component replaces the Application component when you create an AIR application with Flex and must always be used as the initial window in your Flex application.
ActionScript windows
When you create windows with the NativeWindow class, use the Flash Player stage and display list directly. To add a visual object to a NativeWindow, add the object to the display list of the window stage or to another display object container on the stage.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows
HTML windows
When you create HTML windows, you use HTML, CSS, and JavaScript to display content. To add a visual object to an HTML window, you add that content to the HTML DOM. HTML windows are a special category of NativeWindow. The AIR host defines a
nativeWindow property in HTML windows that provides access to the underlying
NativeWindow instance. You can use this property to access the NativeWindow properties, methods, and events described here.
Note: The JavaScript Window object also has methods for scripting the containing window, such as moveTo() and
close(). Where overlapping methods are available, you can use whichever method that is convenient.
Flex Framework windows
The Flex Framework defines its own window components. These components, mx:WindowedApplication and mx:Window, cannot be used outside the framework and thus cannot be used in HTML-based AIR applications.
The initial application window
The first window of your application is automatically created for you by AIR. AIR sets the properties and content of the window using the parameters specified in the
initialWindow element of the application descriptor file.
If the root content is a SWF file, AIR creates a NativeWindow instance, loads the SWF file, and adds it to the window stage. If the root content is an HTML file, AIR creates an HTML window and loads the HTML.
85

Native window classes

Adobe AIR 1.0 and later
The native window API contains the following classes:
Package Classes
flash.display
flash.events
NativeWindow
NativeWindowInitOptions
NativeWindowDisplayState
NativeWindowResize
NativeWindowSystemChrome
NativeWindowType
NativeWindowBoundsEvent
NativeWindowDisplayStateEvent
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows

Native window event flow

Adobe AIR 1.0 and later
Native windows dispatch events to notify interested components that an important change is about to occur or has already occurred. Many window-related events are dispatched in pairs. The first event warns that a change is about to happen. The second event announces that the change has been made. You can cancel a warning event, but not a notification event. The following sequence illustrates the flow of events that occurs when a user clicks the maximize button of a window:
1 The NativeWindow object dispatches a displayStateChanging event.
2 If no registered listeners cancel the event, the window maximizes.
3 The NativeWindow object dispatches a displayStateChange event.
In addition, the NativeWindow object also dispatches events for related changes to the window size and position. The window does not dispatch warning events for these related changes. The related events are:
a A move event is dispatched if the top, left corner of the window moved because of the maximize operation.
b A resize event is dispatched if the window size changed because of the maximize operation.
A NativeWindow object dispatches a similar sequence of events when minimizing, restoring, closing, moving, and resizing a window.
86
The warning events are only dispatched when a change is initiated through window chrome or other operating­system controlled mechanism. When you call a window method to change the window size, position, or display state, the window only dispatches an event to announce the change. You can dispatch a warning event, if desired, using the window
dispatchEvent() method, then check to see if your warning event has been canceled before
proceeding with the change.
For detailed information about the window API classes, methods, properties, and events, see the Adobe AIR API
Reference for HTML Developers.

Properties controlling native window style and behavior

Flash Player 9 and later, Adobe AIR 1.0 and later
The following properties control the basic appearance and behavior of a window:
type
systemChrome
transparent
owner
When you create a window, you set these properties on the NativeWindowInitOptions object passed to the window constructor. AIR reads the properties for the initial application window from the application descriptor. (Except the
type property, which cannot be set in the application descriptor and is always set to normal.) The properties cannot
be changed after window creation.
Some settings of these properties are mutually incompatible: systemChrome cannot be set to standard when either
transparent is true or type is lightweight.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows
Window types
Adobe AIR 1.0 and later
The AIR window types combine chrome and visibility attributes of the native operating system to create three functional types of window. Use the constants defined in the NativeWindowType class to reference the type names in code. AIR provides the following window types:
Type Description
87
Normal A typical window. Normal windows use the full-size style of chrome and appear on the Windows taskbar and
Utility A tool palette. Utility windows use a slimmer version of the system chrome and do not appear on the Windows
Lightweight Lightweight windows have no chrome and do not appear on the Windows taskbar or the Mac OS X window
the Mac OS X window menu.
taskbar and the Mac OS X window menu.
menu. In addition, lightweight windows do not have the System (Alt+Space) menu on Windows. Lightweight windows are suitable for notification bubbles and controls such as combo-boxes that open a short-lived display area. When the lightweight
type is used, systemChrome must be set to none.
Window chrome
Adobe AIR 1.0 and later
Window chrome is the set of controls that allow users to manipulate a window in the desktop environment. Chrome elements include the title bar, title bar buttons, border, and resize grippers.
System chrome
You can set the systemChrome property to standard or none. Choose standard system chrome to give your window the set of standard controls created and styled by the user’s operating system. Choose chrome for the window. Use the constants defined in the NativeWindowSystemChrome class to reference the system chrome settings in code.
System chrome is managed by the system. Your application has no direct access to the controls themselves, but can react to the events dispatched when the controls are used. When you use standard chrome for a window, the
transparent property must be set to false and the type property must be normal or utility.
none to provide your own
Custom chrome
When you create a window with no system chrome, then you must add your own chrome controls to handle the interactions between a user and the window. You are also free to make transparent, non-rectangular windows.
Window transparency
Adobe AIR 1.0 and later
To allow alpha blending of a window with the desktop or other windows, set the window transparent property to
true. The transparent property must be set before the window is created and cannot be changed.
A transparent window has no default background. Any window area not containing an object drawn by the application is invisible. If a displayed object has an alpha setting of less than one, then anything below the object shows through, including other display objects in the same window, other windows, and the desktop.
Transparent windows are useful when you want to create applications with borders that are irregular in shape or that “fade out” or appear to be invisible. However, rendering large alpha-blended areas can be slow, so the effect should be used conservatively.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows
Important: On Linux, mouse events do not pass through fully transparent pixels. You should avoid creating windows with large, fully transparent areas since you may invisibly block the user’s access to other windows or items on their desktop. On Mac OS X and Windows, mouse events do pass through fully transparent pixels.
Transparency cannot be used with windows that have system chrome. In addition, SWF and PDF content in HTML may not display in transparent windows. For more information, see
Considerations when loading SWF or PDF
content in an HTML page” on page 48.
The static NativeWindow.supportsTransparency property reports whether window transparency is available. When transparency is not supported, the application is composited against a black background. In these cases, any transparent areas of the application display as an opaque black. It is a good practice to provide a fallback in case this property tests
false. For example, you could display a warning dialog to the user, or display a rectangular, non-
transparent user interface.
Note that transparency is always supported by the Mac and Windows operating systems. Support on Linux operating systems requires a compositing window manager, but even when a compositing window manager is active, transparency can be unavailable because of user display options or hardware configuration.
Transparency in an HTML application window
Adobe AIR 1.0 and later
88
By default the background of HTML content displayed in HTML windows and HTMLLoader objects is opaque, event if the containing window is transparent. To turn off the default background displayed for HTML content, set the
paintsDefaultBackground property to false. The following example creates an HTMLLoader and turns off the
default background:
var htmlView:HTMLLoader = new HTMLLoader(); htmlView.paintsDefaultBackground = false;
This example uses JavaScript to turn off the default background of an HTML window:
window.htmlLoader.paintsDefaultBackground = false;
If an element in the HTML document sets a background color, the background of that element is not transparent. Setting a partial transparency (or opacity) value is not supported. However, you can use a transparent PNG-format graphic as the background for a page or a page element to achieve a similar visual effect.
Window ownership
One window can own one or more other windows. These owned windows always appear in front of the master window, are minimized and restored along with the master window, and are closed when the master window is closed. Window ownership cannot be transfered to another window or removed. A window can only be owned by one master window, but can own any number of other windows.
You can use window ownership to make it easier to manage windows used for tool palettes and dialogs. For example, if you displayed a Save dialog in association with a document window, making the document window own the dialog will keep the dialog in front of the document window automatically.
NativeWindow.owner
Christian Cantrell: Owned windows in AIR 2.6
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows

A visual window catalog

Adobe AIR 1.0 and later
The following table illustrates the visual effects of different combinations of window property settings on the Mac OS X, Windows, and Linux operating systems:
89
Window settings Mac OS X Microsoft Windows Linux
Type: normal
SystemChrome: standard
Transparent: false
Type: utility
SystemChrome: standard
Transparent: false
*
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows
90
Window settings Mac OS X Microsoft Windows Linux
Type: Any
SystemChrome: none
Transparent: false
Type: Any
SystemChrome: none
Transparent: true
mxWindowedApplication or mx:Window
Type: Any
SystemChrome: none
Transparent: true
*
*
Ubuntu with Compiz window manager
Note: The following system chrome elements are not supported by AIR: the Mac OS X Toolbar, the Mac OS X Proxy Icon, Windows title bar icons, and alternate system chrome.

Creating windows

Adobe AIR 1.0 and later
AIR automatically creates the first window for an application, but you can create any additional windows you need. To create a native window, use the NativeWindow constructor method.
To create an HTML window, either use the HTMLLoader createRootWindow() method or, from an HTML document, call the JavaScript list contains an HTMLLoader object. The HTMLLoader object interprets and displays the HTML and JavaScript content for the window. You can access the properties of the underlying NativeWindow object from JavaScript using
window.nativeWindow property. (This property is only accessible to code running in the AIR application
the sandbox.)
window.open() method. The window created is a NativeWindow object whose display
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows
When you initialize a window—including the initial application window—you should consider creating the window in the invisible state, loading content or executing any graphical updates, and then making the window visible. This sequence prevents any jarring visual changes from being visible to your users. You can specify that the initial window of your application should be created in the invisible state by specifying the application descriptor (or by leaving the tag out altogether since
false is the default value). New NativeWindows are
invisible by default. When you create an HTML window with the HTMLLoader can set the
true to make a window visible.
visible argument to false. Call the NativeWindow activate() method or set the visible property to
<visible>false</visible> tag in the
createRootWindow() method, you

Specifying window initialization properties

Adobe AIR 1.0 and later
The initialization properties of a native window cannot be changed after the desktop window is created. These immutable properties and their default values include:
Property Default value
systemChrome standard
type normal
91
transparent false
owner null
maximizable true
minimizable true
resizable true
Set the properties for the initial window created by AIR in the application descriptor file. The main window of an AIR application is always type, normal. (Additional window properties can be specified in the descriptor file, such as
visible, width, and height, but these properties can be changed at any time.)
Set the properties for other native and HTML windows created by your application using the NativeWindowInitOptions class. When you create a window, you must pass a NativeWindowInitOptions object specifying the window properties to either the NativeWindow constructor function or the HTMLLoader
createRootWindow() method.
The following code creates a NativeWindowInitOptions object for a utility window:
var options = new air.NativeWindowInitOptions(); options.systemChrome = air.NativeWindowSystemChrome.STANDARD; options.type = air.NativeWindowType.UTILITY options.transparent = false; options.resizable = false; options.maximizable = false;
Setting systemChrome to standard when transparent is true or type is lightweight is not supported.
Note: You cannot set the initialization properties for a window created with the JavaScript window.open() function. You can, however, override how these windows are created by implementing your own HTMLHost class. See
Handling
JavaScript calls to window.open()” on page 61 for more information.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows

Creating the initial application window

Adobe AIR 1.0 and later
Use a standard HTML page for the initial window of your application. This page is loaded from the application install directory and placed in the application sandbox. The page serves as the initial entry point for your application.
When your application launches, AIR creates a window, sets up the HTML environment, and loads your HTML page. Before parsing any scripts or adding any elements to the HTML DOM, AIR adds the
nativeWindow properties to the JavaScript Window object. You can use these properties to access the runtime classes
from JavaScript. The
nativeWindow property gives you direct access to the properties and methods of the desktop
window.
The following example illustrates the basic skeleton for the main page of an AIR application built with HTML. The page waits for the JavaScript window
<html> <head> <script language="javascript" type="text/javascript" src="AIRAliases.js"></script> <script language="javascript"> window.onload=init;
function init(){ window.nativeWindow.activate(); } </script> </head> <body></body> </html>
load event and then shows the native window.
runtime, htmlLoader, and
92
Note: The AIRAliases.js file referenced in this example is a script file that defines convenient alias variables for the commonly used built-in AIR classes. The file is available inside the
frameworks directory of the AIR SDK.

Creating a NativeWindow

Adobe AIR 1.0 and later
To create a NativeWindow, pass a NativeWindowInitOptions object to the NativeWindow constructor:
var options = new air.NativeWindowInitOptions(); options.systemChrome = air.NativeWindowSystemChrome.STANDARD; options.transparent = false; var newWindow = new air.NativeWindow(options);
The window is not shown until you set the visible property to true or call the activate() method.
Once the window is created, you can initialize its properties and load content into the window using the stage property and Flash display list techniques.
In almost all cases, you should set the stage scaleMode property of a new native window to noScale (use the
StageScaleMode.NO_SCALE constant). The Flash scale modes are designed for situations in which the application
author does not know the aspect ratio of the application display space in advance. The scale modes let the author choose the least-bad compromise: clip the content, stretch or squash it, or pad it with empty space. Since you control the display space in AIR (the window frame), you can size the window to the content or the content to the window without compromise.
The scale mode for HTML windows is set to noScale automatically.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows
Note: To determine the maximum and minimum window sizes allowed on the current operating system, use the following static NativeWindow properties:
var maxOSSize = air.NativeWindow.systemMaxSize; var minOSSize = air.NativeWindow.systemMinSize;

Creating an HTML window

Adobe AIR 1.0 and later
To create an HTML window, you can either call the JavaScript Window.open() method, or you can call the AIR HTMLLoader class
HTML content in any security sandbox can use the standard JavaScript Window.open() method. If the content is running outside the application sandbox, the as a mouse click or keypress. When at the specified URL. For example:
newWindow = window.open("xmpl.html", "logWindow", "height=600, width=400, top=10, left=10");
Note: You can extend the HTMLHost class in ActionScript to customize the window created with the JavaScript
window.open() function. See “About extending the HTMLHost class” on page 52.
createRootWindow() method.
open() method can only be called in response to user interaction, such
open() is called, a window with system chrome is created to display the content
93
Content in the application security sandbox has access to the more powerful method of creating windows,
HTMLLoader.createRootWindow(). With this method, you can specify all the creation options for a new window. For
example, the following JavaScript code creates a lightweight type window without system chrome that is 300x400 pixels in size:
var options = new air.NativeWindowInitOptions(); options.systemChrome = "none"; options.type = "lightweight";
var windowBounds = new air.Rectangle(200,250,300,400); newHTMLLoader = air.HTMLLoader.createRootWindow(true, options, true, windowBounds); newHTMLLoader.load(new air.URLRequest("xmpl.html"));
Note: If the content loaded by a new window is outside the application security sandbox, the window object does not have the AIR properties:
runtime, nativeWindow, or htmlLoader.
If you create a transparent window, then SWF content embedded in the HTML loaded into that window is not always displayed. You must set the
transparent. The default value of wmode is window, so, by default, SWF content is not displayed in transparent
or windows. PDF content cannot be displayed in transparent windows, no matter which
wmode parameter of the object or embed tag used to reference the SWF file to either opaque
wmode value is set. (Prior to AIR
1.5.2, SWF content could not be displayed in transparent windows, either.)
Windows created with the createRootWindow() method remain independent from the opening window. The
parent and opener properties of the JavaScript Window object are null. The opening window can access the
Window object of the new window using the HTMLLoader reference returned by the In the context of the previous example, the statement
newHTMLLoader.window would reference the JavaScript
createRootWindow() function.
Window object of the created window.
Note: The createRootWindow() function can be called from both JavaScript and ActionScript.
Last updated 9/28/2011
HTML DEVELOPER’S GUIDE FOR ADOBE AIR
Working with AIR native windows

Creating a mx:Window

Adobe AIR 1.0 and later
To create a mx:Window, you can create an MXML file using mx:Window as the root tag, or you can call the Window class constructor directly.
The following example creates and shows a mx:Window by calling the Window constructor:
var newWindow:Window = new Window(); newWindow.systemChrome = NativeWindowSystemChrome.NONE; newWindow.transparent = true; newWindow.title = "New Window"; newWindow.width = 200; newWindow.height = 200; newWindow.open(true);

Adding content to a window

Adobe AIR 1.0 and later
How you add content to an AIR window depends on the type of window. For example, MXML and HTML let you declaratively define the basic content of the window. You can embed resources in the application SWF files or you can load them from separate application files. Flex, Flash, and HTML content can all be created on the fly and added to a window dynamically.
94
When you load SWF content, or HTML content containing JavaScript, you must take the AIR security model into consideration. Any content in the application security sandbox, that is, content installed with your application and loadable with the app: URL scheme, has full privileges to access all the AIR APIs. Any content loaded from outside this sandbox cannot access the AIR APIs. JavaScript content outside the application sandbox is not able to use the
nativeWindow, or htmlLoader properties of the JavaScript Window object.
runtime,
To allow safe cross-scripting, you can use a sandbox bridge to provide a limited interface between application content and non-application content. In HTML content, you can also map pages of your application into a non-application sandbox to allow the code on that page to cross-script external content. See
AIR security” on page 69.
Loading HTML content into a NativeWindow
To load HTML content into a NativeWindow, you can either add an HTMLLoader object to the window stage and load the HTML content into the HTMLLoader, or create a window that already contains an HTMLLoader object by using the
HTMLLoader.createRootWindow()method. The following example displays HTML content within a 300
by 500 pixel display area on the stage of a native window:
//newWindow is a NativeWindow instance var htmlView:HTMLLoader = new HTMLLoader(); htmlView.width = 300; htmlView.height = 500;
//set the stage so display objects are added to the top-left and not scaled newWindow.stage.align = "TL"; newWindow.stage.scaleMode = "noScale"; newWindow.stage.addChild( htmlView );
//urlString is the URL of the HTML page to load htmlView.load( new URLRequest(urlString) );
Last updated 9/28/2011
Loading...