A simple way to get native alerts with Adobe AIR

In an AIR project I am currently working on I wanted to have native alert boxes in my app rather than building custom pop up boxes. There is no built in way to get native alerts in AIR and I remembered reading this interview over at leebrimelow.com a while back where a developer at Illume used StageWebView to trigger an alert from a HTML page. So I decided to make a class called NativeAlert that uses AIR’s HTMLLoader to trigger alerts.

The class supports all three JavaScript pop ups – Alert, Confirm and Prompt. Here is how to use each popup:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Create the NativeAlert object
var nativeAlert:NativeAlert = new NativeAlert();


/* basic alert
 *
 * alert(message:String):void
 *
*/

nativeAlert.alert("Hello there!");


/* confirm box
 *
 * confirm(message:String):Boolean
 *
*/

if (nativeAlert.confirm("Would you like to proceed?"))
{
    //do domething
}
else
{
    // the user cancelled
}


/* prompt box
 *
 * promt(message:String,defaultValue:String):String
 *
*/

var userName:String = nativeAlert.promt("please enter your name:", "");

And here is the class – copy the code into a new ActionScript file called NativeAlert.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package
{
    import flash.html.HTMLLoader;
   
    /**
     * ...
     * @author Ben Foster
     *      -web: www.nemenvisual.com
     *      -blog: www.purplesquirrels.com.au
     */

    public class NativeAlert
    {
        private var _alertDispatcher:HTMLLoader;
        private var _html:String ="<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'>" +
                    "<title></title><script></script></head><body></body></html>";
           
        public function NativeAlert()
        {
            _alertDispatcher = new HTMLLoader();
            _alertDispatcher.loadString(_html);
        }
       
        // invokes an alert box
        public function alert(message:String):void
        {
            _alertDispatcher.window.alert(message);
        }

        // invokes a confirm box       
        public function confirm(message:String):Boolean
        {
            return _alertDispatcher.window.confirm(message);
        }

        // invokes a prompt box    
        public function prompt(message:String,defaultVal:String=""):String
        {
            return _alertDispatcher.window.prompt(message, defaultVal);
        }
       
    }

}
Posted toActionScript AIR Flash Javascript