BKWLD

 

Handling remote content with Loader class and security

By Ben on December 21, 2007 at 1:12 pm

Doing some work with Flickr’s API and Actionscript 3 today. When I finally exported my file, the Event.INIT associated with the Loader didn’t seem to be firing the way I thought it would. I was resizing an image after it had initialized, but it seemed to only work in the Flash IDE. Here’s what I started with:

private var _image:Bitmap;

public function Image (url:String):void  {
	loader = new Loader();
	loader.contentLoaderInfo.addEventListener(Event.INIT, onInit);
        addChild(loader);
        var request:URLRequest = new URLRequest(url);
        loader.load(request);
}

private function onInit (event:Event):void {
        _image = Bitmap(event.target.content);
}

This code works great for loading an image on a local server or in the flash player, but my code to resize the image on init was not being run when the movie was embedded in a browser. So, I added this and figured out that it was throwing an error:

private function onInit (event:Event):void {
        try{
                _image = Bitmap(event.target.content);
        } catch (error:SecurityError) {
                trace(error);
        }
}

This basically “trys” to access the content of the loader and if it can’t, throws a SecurityError (#2122). Flickr has a crossdomain.xml file that allows all access (”*”) so I was confused as to why it was throwing this error. Turns out with AS3 that you have to TELL it to check the crossdomain file. So, my new load function now looks like this:

var context:LoaderContext = new LoaderContext(true);
var request:URLRequest = new URLRequest(url);
loader.load(request, context);

The “true” param in LoaderContext let’s Loader know that it should checkPolicyFile. Trouble is, even after checking the policy file, I was still getting the SecurityError. Finally, with all this data in hand, I did some googling and found this. Seems that perhaps there’s some kind of redirect on the asset we are accessing, so we need to continue to hit the url with the policy file to get a valid asset. Here’s what the final init function looks like (in general):

private function onInit (event:Event):void {
	if (event.target.childAllowsParent == false) {
		load(event.target.url);
	} else {
		_image = Bitmap(event.target.content);
		dispatchEvent(new Event(Event.INIT));
	}
}

I had thought it was another Event.INIT firing problem but it turns out it was a sandbox violation.

No Comments »

No comments yet.


RSS feed for comments on this post. | TrackBack URI

Leave a comment