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.
Intermediate
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.
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.
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();">
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.
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:
On Mac OS X, the ExternalInterface object is supported in the following browsers:
Flash Player for Linux version 9.0.31.0 and later supports the ExternalInterface class in the following browsers:
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.
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.
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.
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.

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.
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.
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.
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.
Tutorials and samples |
| 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 |