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:

// 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.

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 = "<script></script>";

    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);
    }
  }
}