Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Dreamweaver Developer Center /

Integrating Flash content with the HTML environment

by Dan Carr

Dan Carr
  • Dan Carr Design

Created

7 April 2008

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
Dreamweaver CS3 Flash Professional CS3 HTML JavaScript SWF website workflow

Requirements

Prerequisite knowledge

This article covers basic concepts in JavaScript and Flash integration using Dreamweaver and Flash. Although no prior experience is necessary, familiarity with both Dreamweaver and Flash is recommended.

User Level

Intermediate

Required products

  • Flash Professional (Download trial)
  • Dreamweaver (Download trial)

Sample files

  • flash_integration.zip (542 KB)

Working with Flash content has become part of the process for many web developers whether the content is a small element on the page or the entire page. Knowing how to use Dreamweaver to integrate your Flash content with the HTML environment will allow you to create rich user interfaces and handle many tasks related to interface design.

This article provides an overview of some strategies for integrating Flash content with HTML content. You'll look at the code in Dreamweaver and Flash to get a clear picture of how things fit together.

Integrating Flash content with HTML using JavaScript

JavaScript is a scripting language that lives within and has control over the HTML environment. JavaScript is interpreted by most browsers and does not require a plug-in as Flash and ActiveX controls do. It's generally used to provide programming logic to the HTML page. Many web applications—such as banner ad systems, e-commerce sites, and e-learning SCORM-compliant courses—use JavaScript as a standard technology. JavaScript is the link between Flash content and the larger APIs of these types of applications.

Using a few easy steps, you can make your Flash content communicate with the JavaScript you use in Dreamweaver and vice versa.

Preparing your HTML page

Dreamweaver is a great tool for writing JavaScript. You can either write the code directly into your HTML page or write the code in a separate JavaScript file, which is referenced in your HTML page. For simple scripts, I usually write the JavaScript code directly on the page. For complex scripts or scripts that I will use repeatedly across web pages, I'll write the JavaScript code in a separate file.

When preparing to work with Flash content you can add two generic JavaScript functions to get started. I usually begin by adding the following code:

<script language="javascript"> function getFlashContent( name ) { if (navigator.appName.indexOf("Microsoft") != -1) { return window[name]; } else { return document[name]; } } function init(){ // add code here... } </script>

The getFlashContent function is a generic utility that allows you to identify the path to the Flash movie on Internet Explorer or Mozilla browsers. Whenever you need to reference the Flash movie, you call this function and pass in the name given to the Flash movie in the object or embed tag. The init function is a generic hook for integrating functionality that is required to occur when the page loads. I usually call the init function during the onload event for the HTML page, which in turn ensures that the Flash movie is available before attempting to access it. I use the following code in the body tag of the HTML page to create the hook:

<body onload="init();">

Preparing your Flash content

Although Flash content (SWF) can be exported from many authoring tools other than Flash, I recommend building your content in Flash CS3 to achieve the best results. The problem with using tools other than Flash is that you may not be able to add the JavaScript-related ActionScript code and you won't have control over the structure of the content in the file.

Tip: If you don't have an editable source file for the Flash movie, you can create a wrapper movie in Flash that loads the content SWF. This strategy allows you to add your code to the main Timeline. The sample at the end of this section demonstrates how to accomplish this.

Working with the ExternalInterface object in Flash

Flash uses the ExternalInterface object in ActionScript as a simple way to interact with JavaScript. The ExternalInterface object is easy to use and has the ability to send and receive calls. By defining a simple API, you can expose Flash data and functionality to JavaScript and control the browser environment from Flash.

Let's say that you have a JavaScript function named setScore on the web page that contains the Flash movie. The setScore function accepts a single parameter as the score value:

<script language="javascript"> function setScore( i ) { score = i; } </script>

In Flash, you would calculate the score and write the following line of code in ActionScript:

ExternalInterface.call("setScore",80);

The ExternalInterface call command accepts one or more parameters, (the first parameter is the name of the JavaScript function and the following optional parameters are values being passed to the JavaScript function). If you're not passing any values to the JavaScript function you only need to supply the function name as the first argument. In the sample above, Flash is passing the score value of 80 to the setScore JavaScript function.

Tip: The call command can be used to return data from the JavaScript function as well. This is a handy feature when you need to retrieve information about the user's browser or the JavaScript tracking environment.

Let's say that you have a JavaScript function named finishGame that needs to retrieve score data from the Flash movie. The JavaScript function receives the data by calling an ActionScript function in the Flash movie. Here's how the JavaScript would look if the JavaScript called a Flash function named getScore:

<script language="javascript"> function finishGame() { getFlashContent("myGame").getScore(); } </script>

To make this work, the Flash movie uses ActionScript to register the getScore function as being available to the HTML container. The following ActionScript is added in Flash to complete the setup:

function getScore() { return score; } ExternalInterface.addCallBack("getScore",getScore);

The ExternalInterface addCallBack command registers the ActionScript function as being available to JavaScript. The first parameter is the name that JavaScript will use and the second parameter is a reference to the related function in ActionScript. I usually use the same name to make things easier, but the two names don't have to be identical.

The syntax and process for working with the ExternalInterface object is the same in ActionScript 2.0 and ActionScript 3.0. The ExternalInterface object is supported in Flash Player 8 and higher on Windows and Mac OS X.

On Windows, the ExternalInterface object is supported in the following browsers:

  • Internet Explorer 5.0 and later
  • Netscape 8.0 and later
  • Mozilla 1.7.5 and later
  • Firefox 1.0 and later

On Mac OS X, the ExternalInterface object is supported in the following browsers:

  • Netscape 8.0 and later
  • Mozilla 1.7.5 and later
  • Firefox 1.0 and later
  • Safari 1.3 and later

Flash Player for Linux version 9.0.31.0 and later supports the ExternalInterface class in the following browsers:

  • Mozilla 1.7.x and later
  • Firefox 1.5.0.7 and later
  • SeaMonkey 1.0.5 and later

For more information on the ExternalInterface object, refer to the following page of the online Flash documentation: ActionScript 3.0 Language and Components Reference > ExternalInterface.

Note: Older methods of calling JavaScript from Flash include the fscommand and getURL commands in ActionScript. fscommand can send and receive JavaScript information, but it is not supported on Mac. getURL is supported on Mac and Windows, but it can only send calls to JavaScript; it cannot receive them. Both approaches are backward compatible to FlashPlayer 3 and considered to be deprecated in favor of using the ExternalInterface object. The fscommand command exists in both ActionScript 2.0 and ActionScript 3.0 whereas the getURL command only exists in ActionScript 2.0.

Example #1: Dynamic banner loader

Now that you've reviewed all of the elements, take a look at the following sample project.

Sample 1 shows how a dynamic banner loader might work. Like many real world banner systems, the list of banners and navigation control is handled by JavaScript on the HTML page. This version uses an invisible Flash movie as a loading utility that creates a transition animation for each banner, tracks the time the banner has been onscreen, and signals the JavaScript system when the duration of the banner has elapsed. The JavaScript and the Flash movie work together to load a series of GIF banner images.

The banner loader implements a very simple API. The JavaScript is expected to expose a getBanner function that the Flash movie can call. The Flash movie is expected to expose a setBanner and setDelay function that the JavaScript can call. Here's a breakdown of the functions involved and a description of each:

  • getBanner: Called by Flash to signal that a new banner is ready to be loaded.
  • setDelay(i): Called by JavaScript to set the delay time between banners (in milliseconds).
  • setBanner(path): Called by JavaScript to trigger loading the specified path.

Review the following JavaScript code to see the getBanner function:

<script language="javascript"> function getFlashContent(name) { if (navigator.appName.indexOf("Microsoft") != -1) { return window[name]; } else { return document[name]; } } function getBanner() { index++; if( index == banners.length ){ index = 0; } loader.setBanner(banners[index]); } function init() { // Set delay & start! loader = getFlashContent("banner_loader"); loader.setDelay(4000); loader.setBanner(banners[index]); } var loader; var index = 0; var banners = ["Images/banner1.gif","Images/banner2.gif","Images/banner3.gif"]; </script>

The JavaScript code is responsible for creating (acquiring) a list of banner images and keeping track of which image is currently loaded. The init function sets a delay time of 4 seconds and loads the first banner when the page loads. The getBanner function is called when the Flash movie reaches its delay limit or decides the timing needs to advance. When the getBanner function is triggered, it loads the next banner in the list or loops back to the beginning.

Now take a look at the following ActionScript 3.0 code:

//***************************** // Security (set to open-access) flash.system.Security.allowDomain("*"); //***************************** // Loading event handlers... function delayHandler():void { // Load next banner after the delay ExternalInterface.call("getBanner"); } //***************************** // JavaScript hooks function setDelay(n:Number):void { delay = n; } function setBanner(bPath:String):void { loader.load(new URLRequest(bPath)); } // Expose to JavaScript ExternalInterface.addCallback("setDelay", setDelay); ExternalInterface.addCallback("setBanner", setBanner);

The Flash code loads the banner and creates the transition animation, handles the timing delay code that notifies the JavaScript when to move forward, and then registers the JavaScript accessible function code with the container.

The ActionScript sample above contains only the JavaScript-related Flash code. Refer to the Sample1.fla source file, included with the sample files that accompany this article, for the complete code sample.

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.

More Like This

  • Turning a design into HTML and CSS using the Fireworks to Dreamweaver workflow – Part 2: Modifying the HTML and CSS
  • Scripting the web – Part 2: Introduction to jQuery
  • Working with Drupal in Dreamweaver CS5
  • Styling and inserting a Spry Menu Bar 2.0 widget with the Adobe Widget Browser
  • Turning a design into HTML and CSS using the Fireworks to Dreamweaver workflow – Part 1: Exporting the design
  • HTML5 and CSS3 in Dreamweaver CS5.5 – Part 3: Using CSS media queries to target different screen resolutions
  • HTML5 and CSS3 in Dreamweaver CS5.5 – Part 2: Styling the web page
  • Understanding Spry basics
  • Scripting the web – Part 1: Introduction to JavaScript
  • Excerpt: Bring Your Web Design to Life

Tutorials and samples

Tutorials

  • Understanding HTML5 semantics: Changed and absent elements
  • Mobile app with PhoneGap: Submitting to the Apple App Store
  • PhoneGap and Dreamweaver: Releasing on iOS
  • Mobile app with PhoneGap: Submitting to Android Market

Samples

  • Responsive design with jQuery marquee
  • Customizable starter design for jQuery Mobile
  • Customizable starter design for HTML5 video
  • Customizable starter design for multiscreen development

Dreamweaver user forum

More
04/23/2012 Resolution/Compatibility/liquid layout
04/20/2012 using local/testing server with cs5 inserting images look fine in the split screen but do not show
04/18/2012 Ap Div help
04/23/2012 Updating

Dreamweaver Cookbook

More
11/07/2011 Simple social networking share buttons
09/20/2011 Registration form that will generate email for registrant to validate
08/21/2011 Spry Accordion - Vertical Text - Auto Start on Page Load - Mouse Over Pause
08/17/2011 Using cfdump anywhere you like

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement