Opening Links in Flash

Opening links to web pages from AS3 is pretty well covered in various online documentation.  It’s similarly straightforward in Haxe.  Recently, however, I came to realize that it wasn’t normal Flash behavior that Haxe programs would only open links in the browser or standalone player if served from a server,  even localhost, and not from a local ‘file:’ URL.

It turned out this was because Haxe by default compiles to a different, more restricted network security model than that to which the Adobe tools compile.  Even if opened from a MouseEvent, the navigation calls are blocked, as is all network access from a local SWF.  To enable this network access and allow links to be opened, you have to compile with the network-sandbox compiler flag (-Dnetwork-sandbox).  The documentation for it is a little non-intuitively ambiguous, but that actually enables more access than the default.  Links should now all work, from a hosted or local SWF.

As a sidenote, the code to open a link in Haxe looks like this:

import flash.Lib;
import flash.text.TextField;
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.events.MouseEvent;
import flash.events.Event;

class Sample extends Sprite
{
   public function new()
   {
      super();

      Lib.current.stage.addChild(this);

      var label:TextField=new TextField();
      label.width=800;
      label.text="Click to open google!";
      addChild(label);
      Lib.current.stage.addEventListener(MouseEvent.CLICK,onClick);
   }

   public function onClick(inEvent:MouseEvent)
   {
     Lib.getURL(new URLRequest("http://www.google.com"));
   }

   public static function main()
   {
     new Sample();
   }
}

Its equivalent in AS3 looks like the following:

package {

  import flash.display.Sprite;
  import flash.text.TextField;
  import flash.net.URLRequest;
  import flash.events.MouseEvent;
  import flash.events.Event;

  import flash.net.navigateToURL;
  import flash.net.URLRequest;

 public class LinkTest extends Sprite {
    public function LinkTest() {
      var label:TextField = new TextField();
      label.width = 200;
      label.text = "Click here";
      addChild(label);


      label.addEventListener(MouseEvent.CLICK, onClick);
    }


    public function onClick(e:MouseEvent) {
      navigateToURL(new URLRequest("http://google.com"));
    }
  }
}

Internally Haxe’s flash.Lib is actually literally just calling navigateToURL via a pretty wild looking cast on the global symbol table entry, since Haxe has no concept of package level functions like AS3 does.