Making SWFs Aware of Browser Sessions
In my previous post about the Nascar slideshow, I mentioned how the module had variant behavior based on whether you had seen it or not during the current browser session. Though I briefly described the process to make this happen, I've decided to share example code of how this is done.
What is a Browser Session?
First off, when I speak of a browser session it is important to know exactly what I mean. Loosely defined, a browser session is the time duration from the point at which a session is started (while the browser is open) until all instances of that browser are closed. A session typically can be started by setting the session on entrance to a site, at login to a site, or at some other predetermined time.
Does a SWF know about a Browser Session?
A SWF has no internal way of knowing whether it was being visited another time by navigating in the same browser (page forward, page back, page refresh, etc), or whether it is the initial visit by a fresh browser instance. This lack of knowing presents an issue of being able to act on a temporary browser session. Essentially, the SWF doesn't know when or how it was opened. For example, setting a Shared Object and reading it, you don't have a way to clear it when a browser closes (without help) or know whether it was set before you restarted your computer. Thus it knows nothing of its opening relationship, only that it was opened. Instead, the information has to be given to the SWF by the browser, since the browser is aware of it.
Making the SWF aware of the Browser Session
In order to do make the SWF aware of the session, you can create a browser based session cookie (a temporary cookie that is removed when the browser is closed). You can then pass the existance of this cookie into the SWF as a FlashVar with a Boolean value. If it exists you know that you are in a current session, if not the SWF is being opened for the first time in this particular browser instance. The timing at which you do this is important, as you want to write out the SWF first, then create the session cookie so it is available for subsequent embeds .
EXAMPLE CODE:
Using SWFObject, adding the session information to a swf is pretty easy to do:
// session flag to swf
so.addVariable("FLASHVARS_hasSession", (document.cookie.indexOf("session=exists")!=-1) ? "true" : "false");
so.write("sessionDiv");
// set session
document.cookie = "session=exists;";
A working example can be seen here.