Thursday 22 October 2009

FLEX - Getting the URL when you are in a flex App

There are times when you want to get the URL either in it's entirity or just bits of it inside Flex. For example when you want to send a link to a document so that flex knows to go to that particular document and open it when the Flex app is initiated.

This is relatively simiple all you need to do is instansiate and access the BrowserManager object, from this object you can get all sorts of useful information about the URL that holds the FLEX object.

You will need to import the following classes.
import mx.utils.URLUtil;
import mx.managers.IBrowserManager;
import mx.managers.BrowserManager;
and the declare vars for the bits of the URL you want to get at
private var serverName:String;
private var portName:int;
private var protocolName:String;
Then in your application.CreationComplete event function lets call it initApp() you need this
private function initApp():void
(
browserManager = BrowserManager.getInstance();
browserManager.init("", "Browser Window Title");
var url:String = browserManager.url;
serverName = mx.utils.URLUtil.getServerName(url);
portName = mx.utils.URLUtil.getPort(url);
protocolName = mx.utils.URLUtil.getProtocol(url);
}

You then have your current server url all nicely in vars and you do not need to hard code your URLs in the rest of the code. (you will need to make the vars [Bindable] if you want to use them in other objects!)

There are loads of other methods associated with the BrowserManager Class which you can find here.

Disqus for Domi-No-Yes-Maybe