Flex Pasta » Flex and Javascript
Whether I am tracking how long a user’s session lasts, trying to decrease JVM memory usage, or am debugging a user’s problem, I want to know, and end immediately the user’s Java session when they(the user) logs out of my flex application. When they click my big red “Log Out” button like every good user is supposed to then I can end the user’s session easily by calling a remote service that does
try
{
FlexContext.getFlexSession().getSession(false).invalidate();
}
catch(IllegalStateException i)
{
System.Out.Println("I'm trying to invalidate the session but it seems to be dead already. Oh and I'm also using System Out which is not such a great idea, but hey, this is just an example!!!");
}
Now evil Sam comes along and doesn’t press the nifty log out button I so thoughtfully left for him. Instead he navigates away or closes his browser. How to catch this in flex? First, I must have an html wrapper around my swf file. If I don’t, this solution has no basis. In the html wrapper file, find the body tag and add an “onunload” attribute.
<body onunload=”MyFlexApp.myFlexFunction();”>
Then in myFlexFunction(the one inside your swf), I can call the normal Logout service just as if they pressed the logout button.
So you’re coding up your flex app and you want to pass a url parameter into your application. Like getting the color parameter from mydomain.com?color=red. While one option is to call the built in flex option of Application.application.parameters, this will only work if your example points directly to the swf. If your url is main.swf?color=red then Application.application.parameters.color will work fine for you. However, if like most people, have the swf wrapped in an html page(main.html?color=red), this approach won’t work. I ran into this problem myself, and I didn’t want to get into the messy business of editing the flash vars, especially if I had a large number of parameters or wanted to add more on the fly later. I created a HTTPUtil class in actionscript to get the url information. The class uses javascript to get all of the url information, including host name, port, and url parameters among other things. The most helpful method you will find is getParameterValue(key:String):String which will give you back the parameter value for the given key.
Have multiple environments and need to get the full url with the host name and port in actionscript?
There are several methods to help with this:
getHostName()
getPort()
getProtocol() -such as http or https
getContext() -The path after the hostname but before the url parameters
Attached is the source. You can see that the methods are all static and use javascript to get the information back to flex. It is designed to get this information regardless of where the flex swf file lives since most people have them embeded in an html file.