Wednesday, February 4, 2009

Passing parameters to a loaded SWF application

Today I was trying to figure out how to load an SWF that contained another Flex Application and embed it into my main application. This is the code that does it:
var loader:SWFLoader = new SWFLoader();
loader.addEventListener(Event.COMPLETE, function(event:Event):void {
    var content:DisplayObject = loader.content;
    uicomponent.addChild(content);
});
loader.load("SWFLoaderApp.swf");

Then once I figured that out, I wanted to know how to pass parameters into the loaded SWF, and here is how that can be done. Change the load line to:
loader.load("SWFLoaderApp.swf?test=hi");

Then in your SWF application code, you should be able to get those parameters like this:
if (application.loaderInfo != null) {
    var url:String = application.loaderInfo.url;
    var qm:int = url.lastIndexOf("?");
    if (qm != -1) {
        var query:String = url.substr(qm + 1);
        var params:Array = query.split("&");
        for (var i:int = 0; i < params.length; i++) {
            var param:String = params[i];
            var nameValue:Array = param.split("=");
            if (nameValue.length == 2) {
                var key:String = nameValue[0];
                var val:String = nameValue[1];
                trace(key + "=" + val);
            }
        }
    }
}

** Update:
After some more testing I noticed that the above code doesn't always reliably work. And here is what I think is happening. When you start up your main application, the Application.application property is set. Then when you load an SWF using the above code, it shares this same application. So, the better way to get at the parameters passed in through the SWFLoader url is to simply get the parameters property right from your second (loaded) application like this:
// inside your loaded swf application
var params:Object = parameters;
trace("test=" + params["test"]);

From reading the documentation on the mx.core.Application page:
There are two sources of parameters: the query string of the Application's URL, and the value of the FlashVars HTML parameter (this affects only the main Application).

I found this blog quite helpful too in solving this problem:
http://rahulmainkar.blogspot.com/2007/11/swfloader-and-nested-application.html.

2 comments:

Anonymous said...

Have you tried listening on Event.INIT rather than Event.COMPLETE? In Colin Moock's book, Essential ActionScript 3.0, Chapter 28 suggests to use the Event.INIT event to determine when an asset can be acessed. Event.COMPLETE only signifies the application has been downloaded but not ready for use.

Dean said...

greetings to all.
I would first like to thank the writers of this blog by sharing information, a few years ago I read a book called Real Estate Investment costa rica in this book deal with questions like this one.