Accessibility

Table of Contents

Integrating Flash content with the HTML environment

Saving information in cookies and shared objects

A useful feature that exists in both JavaScript and Flash is the ability to save persistent information locally on a user's computer. This information is persistent across visits to the site and is often used for book marking, progress tracking, and saving user information like passwords and high scores. Using persistent data is also a great way to save the user interface state.

This section provides an overview of options available for saving persistent data in JavaScript and Flash.

HTTP cookies

JavaScript has the ability to save information in HTTP cookies. Cookies are text strings saved by name onto the user's computer. You can use your browser's settings or security software, such as Norton Antivirus, to manage and remove cookies. You can use JavaScript and other web programming languages to read and write cookies.

One of my favorite features in Dreamweaver is the Snippets panel (see Figure 1). If you want to work with cookies you can simply start a script block in an HTML file or create a new JavaScript (JS) file, and then click the cookie snippets in the Snippets panel to add the code.

The Snippets panel in Dreamweaver lists the provided JavaScript snippets

Figure 1. The Snippets panel in Dreamweaver lists the provided JavaScript snippets.

I typically use the snippet code to get started writing JavaScript, and then I format and modify the code as needed. The functionality I'm using to read and write cookies comes from Dreamweaver and it looks like this:

<script type="text/javascript">
function writeCookie(name, value, hours)
{
    var expire = "";
    if( hours != null )
    {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expire;
}
    
function readCookie(name)
{
    var cookieValue = "";
    var search = name + "=";
      
    if(document.cookie.length > 0)
    { 
        offset = document.cookie.indexOf(search);
        if( offset != -1 )
        { 
          offset += search.length;
          end = document.cookie.indexOf(";", offset);
          if (end == -1) end = document.cookie.length;
          cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}
</script>

Using the Dreamweaver functions is fairly straightforward. If you want to save a cookie named userScore with a value of 80, you would write the following additional line of JavaScript:

writeCookie("userScore", 80, 40);

If you want to retrieve the score data and save it in a variable, you would add another line of JavaScript:

score = readCookie("userScore");

For more information on cookies, refer to the following Netscape support article: Persistent Client State HTTP Cookies.

Working with shared objects in Flash

ActionScript has its own version of an HTTP cookie called a local shared object. Shared objects are similar in functionality to cookies except that they are more powerful in their ability to save ActionScript data types and larger amounts of organized information. Shared objects have an initial file size limit set at 100K and they follow a security model that restricts access to the information by domain and subdomain.

Tip: The file size limit can be adjusted by the viewer using the Adobe Flash Player Settings panel available by right-clicking the SWF file. Each viewer can also block the use of shared objects from a site by using the same mechanism.

Local shared objects are easy to create using ActionScript. The following code creates or retrieves the shared object named sampleLSO and stores it in a variable named lso:

var lso = SharedObject.getLocal("sampleLSO");

ActionScript data can be stored and retrieved through the shared object's data property. If you want to save a score variable so a Flash game can load it whenever the user visits the site you would add the following:

lso.data.score = 80;

Let's say that you want to add code that checks to see if the score has been recorded yet. You would add the following:

if( lso.data.score == undefined ){
    trace("The score value has not been recorded…");
}

Values written to the data property are saved to the hard disc automatically when the movie is closed, but you can force Flash Player to save the data by adding the following code:

lso.flush();

Although you cannot remove a local shared object from the hard disc using ActionScript, you can empty its contents by using the following code:

lso.clear();

Tip: The SharedObject object in ActionScript can be used for connecting to local shared objects, as described here, or to remote shared objects on Flash Media Server.

For more information on local shared objects, refer to the following page in the online Flash documentation: ActionScript 3.0 Language and Components Reference > SharedObject.

Example #2: Tracking page history in Flash content

At this point you are ready to combine the features from the JavaScript and Flash integration section with the persistent data features you just learned about.

Sample 2 shows how tracking paging might work with Flash content. One of the drawbacks of using Flash for paging systems is that it doesn't include a built-in Back button the way a browser does. By using local persistent data, you can save a user's paging history in the shared object or cookie and then navigate forward and backward through the history as desired.

This sample shows a set of navigable pages built in Flash that use both the shared object and the cookie approach. The Flash movie saves its last viewed page in a local shared object and resumes displaying that page every time the user visits the site. The Flash movie also relays page navigation information to JavaScript, which stores a complete page history in a cookie. The HTML page contains two form buttons that trigger the Flash movie to page forward and backward through the history.

The page tracking sample implements a simple API. The JavaScript portion is expected to expose a savePage function that Flash can call to save a page to the history list. Flash is expected to expose a showPage function that can trigger navigation in the Flash movie by a JavaScript call. Here's a breakdown of the functions:

  • savePage(i): Called by Flash to signal navigation and record the page.
  • showPage(i): Called by JavaScript to trigger the Flash movie to navigate to a page.

Take a look at the following JavaScript code:

<script language="javascript">
function getFlashContent(name) {
      if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[name];
      } else {
            return document[name];
      }
}
function writeCookie(name, value, hours)
{
    var expire = "";
    if( hours != null )
    {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expire;
}
    
function readCookie(name)
{
    var cookieValue = "";
    var search = name + "=";
      
     if(document.cookie.length > 0)
     { 
        offset = document.cookie.indexOf(search);
        if( offset != -1 )
        { 
          offset += search.length;
          end = document.cookie.indexOf(";", offset);
          if (end == -1) end = document.cookie.length;
          cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}
    
function savePage(i) {    
    var tmp = historyIndex + 1;
    historyArray.splice(tmp,historyArray.length-tmp);
    historyArray.push(i);
    historyIndex++;
   
writeCookie("pageHistory",historyArray.toString(),40);
}
    
function back() {
    historyIndex--;
    if( historyIndex < 0 ){
        historyIndex = 0;
    } else {
        var i = historyArray[historyIndex];
        getFlashContent("sections").showPage(i);
    }
}
    
function forward() {
    historyIndex++;
    if( historyIndex == historyArray.length ){
        historyIndex = historyArray.length-1;
    } else {
        var i = historyArray[historyIndex];
        getFlashContent("sections").showPage(i);
    }
}
    
function init() {
    var tmp = readCookie("pageHistory");
    if( tmp.indexOf(",") != -1 ){
        historyArray = tmp.split(",");
        historyIndex = historyArray.length-1;
    } else {
        // Default
        historyArray = [1];
    }
}
var historyArray;
var historyIndex = 0; 
</script>

You'll notice that the first three functions were discussed previously and are used to find the Flash movie and handle the cookie. The savePage method is exposed for the Flash content to call in order to record tracking to the page history list. It updates the list and the cookie during navigation (alternately, you could write the cookie once when the page is closed). The forward and back functions are supplied for any page objects that should navigate the page history and trigger a change in the Flash movie. The init function reads the cookie when the page loads and translates the cookie's data from a string to a JavaScript array.

Tip: HTTP cookies are stored in string (text) format. To simulate a list, you can separate values with commas, like this: 1,2,3,4. The sample code saves a list of page numbers as a comma-delaminated string and parses it into a JavaScript array when the page loads.

Now review the following ActionScript 3.0 code:

//*****************************
// Security (set to open-access)
flash.system.Security.allowDomain("*");
//*****************************
// Variables
var pages:Array = ["none","page1","
page2"," page3"," page4"];
var lso:SharedObject =
SharedObject.getLocal("pagingSample");
// Resume last viewed page
if( lso.data.page == undefined ){
    lso.data.page = 1;
}
showPage(lso.data.page);
//*****************************
// Navigation
function showPage(i:Number):void
{
    // Button state
    for(var n:Number=1; n<pages.length; n++){
       
this["page"+n+"_btn"].setSelected(i==n);
    }
    // Save page in shared object
    lso.data.page = i;
    // Show page…
    animations_mc.gotoAndPlay(pages[i]);
}
// Register with JavaScript
ExternalInterface.addCallback("showPage",showPage);
//*****************************
// Mouse events...
function clickHandler(event:MouseEvent):void
{
    switch(event.target)
    {
        case page1_btn:
            showPage(1);
            break;
        case page2_btn:
            showPage(2);
            break;
        case page3_btn:
            showPage(3);
            break;
        case page4_btn:
            showPage(4);
            break;
    }
    // Save history in JavaScript
    ExternalInterface.call("savePage",lso.data.page);
}
page1_btn.addEventListener(MouseEvent.CLICK,clickHandler);
page2_btn.addEventListener(MouseEvent.CLICK,clickHandler);
page3_btn.addEventListener(MouseEvent.CLICK,clickHandler);
page4_btn.addEventListener(MouseEvent.CLICK,clickHandler);

The Flash code loads the shared object to display the page that was viewed last when the user previously visited the site. If the JavaScript calls the showPage function, the Flash movie updates the local shared object and navigates to the page in the user interface. If one of the page buttons is clicked in Flash, the page is shown and the savePage function is called in JavaScript.

The ActionScript sample code above contains only the JavaScript and shared object-related Flash ActionScript. Refer to the Sample2.fla source file provided in the sample files to view the complete sample.

Where to go from here

Check out the JavaScript behaviors, snippets, and documentation available in Dreamweaver CS3.

Now that you know how to tie your Flash content into the HTML environment, try integrating JavaScript functionality with your next Flash project. Try manipulating and controlling pop-up windows and DHTML layers. The possibilities for integration are endless.

Learn more by reading the Flash Developer Center article entitled Using the External API for Flash-JavaScript communication. And to get more sample projects for Flash, check out the Flash Developer Center.