Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
105
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 24

Introduction to getUrl()

getURL() is likely the most common and straightforward method for calling JavaScript. You can use getURL to call a URL and to target the URL to a specific window. However, almost all browsers allow a JavaScript command within the getURL call.

getURL is a global method. You can call it anywhere, from any object. getURL has three parameters, and all of the parameters are strings. The first parameter is the URL. The second parameter is the target window. This can be the name of a frame. The third parameter is the method, where Get and Post are allowed. The last parameter doesn’t do much for you when using JavaScript. However, the second window parameter can be used to target a specific frame’s JavaScript.

A few limitations are involved with getURL. If you use getURL to call JavaScript, the URL is limited to 508 characters.

Here’s an example getURL that contains JavaScript:

getURL(“JavaScript:alert(‘Hello World!’)”);

Here, you have the simple JavaScript keyword preceding the JavaScript command.

If you were to test this within the Flash development environment, it would open a browser window, because the default window self does not exist within the development environment. After the window opens, some browsers display the alert. If the SWF is in the browser, the alert box appears normally, without opening a new browser window.

Creating a JavaScript Command with Nested Variables

Nesting JavaScript variables within a String can be confusing. It can be doubly confusing in ActionScript, because the two languages are so similar.

When you nest string variables, you use both JavaScript’s and ActionScript’s capabilities to discern double and single quotes. Wrapping single quotes inside of double quotes causes the single quotes to remain a string. Likewise, nesting double quotes within single quotes causes the double quotes to remain a string. Neither JavaScript nor ActionScript have a preference for one or the other.

Generally, it is good practice to keep double quotes in your ActionScript and single quotes within any JavaScript the ActionScript is constructing. This way you can always discern quickly what belongs to which language.

It can be very difficult to debug nested quotes. Use the Check Syntax button often in the ActionScript editor as you create your code. Read the error notes; they can be very handy. It is better to catch a nesting problem with a short string than to realize you’ve made an error in a now complex and confusing String construction.

Try It Out

Calling JavaScript via getUrl()

1.Open a new Flash document, name it simpleFLashtoJS.fla, and save it in your work folder.

2.Open the User Interface tab of the Components panel, and drag a Button component to the center of the stage.

598

Putting JavaScript to Work

3.In the Parameters tab of the button’s Properties panel, find the label parameter, and change the word Button to Alert. In the Properties panel, give the button an instance name of myButton.

4.Click the first frame in the timeline, open the Actions panel, and enter the following ActionScript code:

myButton.onRelease = function()

{

getURL(“javascript:alert(‘Hello World’)”);

};

5.Publish the SWF.

6.Upload the SWF to your server.

7.Open the SWF in your favorite browser and click the Alert button.

How It Works

Here you see that you can prefix JavaScript methods with the javascript keyword within the getURL URL parameter.

The code that you called in the preceding exercise is just one line of JavaScript. This is pretty limiting, but you can also use getURL() to call functions that you have written. Consider a web page with the following JavaScript:

<script language=”JavaScript”> function sendMessage(messageText)

{

alert(messageText);

}

</script>

The sendMessage() function can be called from the following getURL() method:

getURL(“sendMessage(\”Hello World\”);”);

The \” characters are needed to escape the inner quotes so that they are sent as part of the getURL() parameter. You can place dynamic data in the URL by referencing a variable:

var browserMessage:String = “Hello World”;

getURL(“sendMessage(\”” + browserMessage + “\”);”);

The quotes start getting messy at this point. The first part of the message, “sendMessage(\””, passes sendMessage(“ to getURL(), the last part passes “); to getURL(), and browserMessage sends Hello World. The end result is that getURL() sees sendMessage(“Hello World”); and passes that to the browser.

One of the limitations of using getURL() to call JavaScript functions is that you can send data as one or more input parameters, but you cannot pass a return value from JavaScript and have it be picked up with ActionScript. You see some techniques for dealing with this shortly.

599

Chapter 24

For now, try using a JavaScript function to interact with the contents of a web page.

Try It Out

Calling a JavaScript Function

In this example you use Flash to rewrite some div content. Use the very latest Firefox browser for this example. The example may work in other browsers but has been tested in Firefox.

1.Open your favorite text editor, and in a new document enter the following JavaScript and HTML code:

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”> <head>

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1” /> <title>callJSfromFlash</title>

<script language=”JavaScript”> <!--

function getVar(divname, divinfo)

{

document.getElementById(divname).innerHTML = divinfo;

}

//--> </script> </head>

2.Save the file as myFlashtoJavaScript.html. You finish this file in step 9.

3.Open a new Flash document and save it as FlashtoJS.fla in your work folder.

4.Open the User Interface tab of the Components panel and drag a Button component to the center of the stage.

5.In the Parameters tab of the button’s Properties panel, find the label parameter and change the word Button to Write HTML. In the Properties panel give the button an instance name of myButton.

6.Click the first frame in the timeline, open the Actions panel, and enter the following ActionScript code:

function writeToDiv(divname, divContent)

{

getURL(“javascript:getVar(‘“+divname+”’,’”+divContent+”’)”);

}

myButton.onRelease = function()

{

var htmlString = ‘<a href=”http://www.gooogle.com”>Google</a><br>’; htmlString += ‘<a href=”http://www.yahoo.com”>Yahoo</a><br>’; htmlString += ‘<a href=”http://www.msn.com”>YMSN</a><br>’; writeToDiv(“widget”, htmlString);

};

7.Publish the SWF with HTML. Be sure that the HTML type is selected in the Publish Settings dialog box.

8.Navigate to your work folder and open the FlashtoJS.html file in your favorite text editor.

600

Putting JavaScript to Work

9.Re-open the myFlashtoJavaScript.html file so that both HTML files are now open. Copy the Object and Embed tags from FlashtoJS.html and place them in myFlashtoJavaScript

.html. myFlashtoJavaScript.html should now look like this:

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”> <head>

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1” /> <title>callJSfromFlash</title>

<script language=”JavaScript”> <!--

function getVar(divname, divinfo)

{

document.getElementById(divname).innerHTML = divinfo;

}

//--> </SCRIPT> </head> <body>

<object classid=”clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” codebase; =”http://fpdownload.macromedia.com/pub/shockwave/cabs/

flash/swflash.cab#version=8,0,0,0” width=”550” height=”400” id=”FlashtoJS” ; align=”middle”>

<param name=”allowScriptAccess” value=”always” />

<param name=”movie” value=”FlashtoJS.swf” /><param name=”quality” value=; “high” /><param name=”bgcolor” value=”#ffffff” /

><embed src=”FlashtoJS.swf” quality=”high” bgcolor=”#ffffff” width=”550” ; height=”400” name=”FlashtoJS” align=”middle”

allowScriptAccess=”always” type=”application/x-shockwave-flash” pluginspage; =”http://www.macromedia.com/go/getflashplayer” />

</object>

<div id=widget>Hello World</div> </body>

</html>

10.Upload myFlashtoJavaScript.html and FlashtoJS.swf to the same directory on a web server.

11.Navigate to the html myFlashtoJavaScript.htm file and test the SWF to JavaScript communication by clicking the button.

How It Works

In this example you created a simple JavaScript function that writes to a div. In JavaScript you can use the document DOM tree to find and target a specific div by id. Then you can replace the content of that div after you’ve found it. Additionally, you could create more divs using the appendChild method of the JavaScript document DOM object.

In this case you’re allowing Flash to control the content of a specific pre-existing div. In your SWF file, you have created a function that contains the getURL object. By creating a string that contains html, you can construct the content of the div directly with ActionScript.

601

Chapter 24

Then you inserted the Object and Embed tags within the document. An important consideration is the allowScriptAccess parameter in the Object and Embed tags. In previous versions of Flash, this value would default to “always” when the parameter did not appear. Because of this, your Flash files could always access JavaScript with little interference. However, with Flash 8, the default value has switched to “sameDomain.” Because of this, if the SWF file were to be hosted on a different domain, or subdomain, the HTML file would block the version 8 SWF from accessing its document, if the allowScriptAccess parameter is allowed to default. Therefore, if you would like an SWF to access your HTML document, you can use the value “always” to give any SWF access to the JavaScript.

Because this example allows any HTML to be written to the div, you could have included any valid HTML code, including style information, and more complex HTML such as child divs, iframes, and more. Because of this, you can think about using SWF files as navigation and interface for HTML content without reloading the SWF file itself.

This idea can be used in conjunction with AJAX methodologies to allow Flash to become a seamless part of your complex HTML-based web applications. Of course, the interaction didn’t need to be just div writes. You can call any JS function you like and send it parameters according to your needs.

getURL() can be a powerful Flash-to-JavaScript communication tool.

Considering Limitations

The main drawback of using getURL() alone is that there is no method for allowing JavaScript to return a success message back to Flash. getURL() is a blind call, the success of which is dependent upon the browser. Also, no precedent exists for using the javascript keyword in a URL within a browser, so support of it is not required by any standard. You should always test your application on your target systems before deploying getURL JavaScript calls. To get a return status, the JavaScript will need to talk to Flash.

Generally, you are limited to 508 characters per JavaScript URL used within getURL. Some browsers are limited to 127 characters, and others are limited to just over 1,000.

Calling JavaScript Functions Using fscommand

One thing you might hear often when implementing the fscommand() from the browser are references to the embed parameter swLiveConnect. This attribute is required for older Netscape browsers; it enabled Java in the browser, which was used to handle fscommand() requests. It isn’t required in newer browsers and is not implemented in the examples.

Another note about fscommand() is that it is not supported in many browsers. For example, IE on a Mac cannot support fscommand(), and there is no work-around. Alternatives to fscommand() will work on far more browsers, but because this is a viable method and is super easy to integrate, you can use it for rapid development where cross-browser support is less of a concern.

602

Putting JavaScript to Work

You can find a more extensive list of fscommand() browser support at www.macromedia.com/ cfusion/knowledgebase/index.cfm?id=tn_14159 . Firefox support can be considered to be equivalent to Netscape 6.2.

The fscommand method works very much like the getURL() method just covered. However, you don’t need to worry about the data length issue that you do with getURL(). The fscommand() function enables you to send arbitrary amounts of data from Flash to the browser. Take a look at how to change the previous exercise so that it uses fscommand() instead of getURL().

Try It Out

Calling a JavaScript Function via fscommand

If you have not done the previous Try It Out example, you should do it now. You should be familiar with a working getURL() example before you decide to use fscommand in an application. You also use the assets created in the previous Try It Out example to make some minor changes to get it to work with fscommand.

1.Re-open the myFlashtoJavaScript.html file. Change your code so that it looks like this:

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”> <head>

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1” /> <title>callJSfromFlash</title>

<SCRIPT LANGUAGE=”JavaScript”> <!--

function FlashtoJS_DoFSCommand(divname, divinfo)

{

document.getElementById(divname).innerHTML = divinfo;

}

//--> </SCRIPT>

<SCRIPT LANGUAGE=”VBScript”> <!--

Sub FlashtoJS_FSCommand(ByVal command, ByVal args) call FlashtoJS_DoFSCommand(command, args)

end sub

//--> </SCRIPT> </head> <body>

<object classid=”clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” codebase=”http:; //fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version@ta =8,0,0,0” width=”550” height=”400” align=”middle” id=FlashtoJS>

<param name=”allowScriptAccess” value=”always” /> <param name=”movie” value=”FSCommandtoJS.swf” /> <param name=”quality” value=”high” />

<param name=”bgcolor” value=”#ffffff” /> <embed src=”FSCommandtoJS.swf”

quality=”high”

bgcolor=”#ffffff”

width=”550”

height=”400”

name=”FlashtoJS”

603

Chapter 24

align=”middle” type=”application/x-shockwave-flash”

pluginspage=”http://www.macromedia.com/go/getflashplayer” /> </object>

<div id=widget>Hello World</div> </body>

</html>

2.Save the HTML file as dofscommand.html.

3.Open a new Flash document and save it as fscommandtoJS.fla in your work folder.

4.Click the first frame in the timeline, open the Actions panel, and enter the following ActionScript code:

fscommand(“widget”, “Hello FSCommand!”);

5.Publish the fscommandtoJS.fla file.

6.Upload dofscommand.html and fscommandtoJS.swf to your server.

7.Navigate to the dofscommand.html file in your browser. You will see the div content now change via the fscommand communication.

How It Works

In this example you were required to create an intermediary function for IE browsers. You then were able to use the parameters sent via fscommand to complete the same task as a getURL JavaScript method.

In this example, because you did not need to construct the JavaScript within Flash, the complexity of sending the variables is lessened. This allows for quicker debugging and faster development.

Of course fscommand() is far more limited than getURL() in that many browsers do not listen for the fscommand — for example, IE on the Mac. As with any Flash-to-JavaScript communication, you should test all of your target systems for compliance and functionality.

Calling Flash from JavaScript

One thing missing from the examples you’ve seen so far is that Flash has no way to tell whether getURL or fscommand were successful.

In the next exercise you use the movie ID that you created in the preceding Try It Out to communicate back to the movie that your function is complete.

Try It Out

Call Flash from JavaScript

This is a simplified example. Before you return a success Boolean, it is wise to ensure that whatever procedure you were looking to complete did, in fact, complete. Because you’re just writing to a div in the example, have the JavaScript immediately return a response to your Flash.

604

Putting JavaScript to Work

You use the dofscommand.html file as well as the fscommandtoJS.fla file from the last example. If you have not completed that Try It Out, you should do it now to understand the fscommand communication.

1.Re-open myFlashtoJavaScript.html. Change your code so that it looks like this:

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”> <head>

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1” /> <title>callJSfromFlash</title>

<SCRIPT LANGUAGE=”JavaScript”> <!--

function FlashtoJS_DoFSCommand(divname, divinfo)

{

alert(divname); document.getElementById(divname).innerHTML = divinfo; document.FlashtoJS.SetVariable(“FSCommandDone”,”true”)

}

//--> </SCRIPT>

<SCRIPT LANGUAGE=”VBScript”> <!--

Sub FlashtoJS_FSCommand(ByVal command, ByVal args) call FlashtoJS_DoFSCommand(command, args)

end sub

//--> </SCRIPT> </head> <body>

<object classid=”clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” codebase=”http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#ver sion=8,0,0,0” width=”550” height=”400” align=”middle” id=FlashtoJS>

<param name=”allowScriptAccess” value=”always” /> <param name=”movie” value=”FSCommandtoJS.swf” /> <param name=”quality” value=”high” />

<param name=”bgcolor” value=”#ffffff” /> <embed src=”FSCommandtoJS.swf”

quality=”high”

bgcolor=”#ffffff”

width=”550”

height=”400”

name=”FlashtoJS”

align=”middle” type=”application/x-shockwave-flash”

pluginspage=”http://www.macromedia.com/go/getflashplayer” />

</object>

<div id=widget>Hello World</div> </body>

</html>

2.

3.

Save the HTML file as JStoFlash.html.

Open the fscommandtoJS.fla from your work folder.

605

Chapter 24

4.Click the first frame in the timeline and create a dynamic textField. Select the text field. In the Var: Parameter in the Properties panel for the field, type the variable name fscommandDone. Leave the ActionScript the same, which should look like the following:

fscommand(“widget”, “Hello FSCommand!”);

5.Publish fscommandtoJS.fla.

6.Upload the JStoFlash.html and fscommandtoJS.swf files to your server.

7.Navigate to the JStoFlash.html file in your browser. You will see the div content now change via the fscommand communication and the word true will appear in your SWF.

How It Works

In this example you saw how JavaScript can communicate with an SWF using the document ID of the Object and Embed tag. In this example you simply set a variable on the root timeline of your SWF via document.FlashtoJS.SetVariable.

From here, you can set an interval or watch method in ActionScript to allow the SWF to make decisions about the variable’s current state.

Basic JavaScript Methods and Events

setVariable is just one method available to JavaScript to control a Flash movie. There is an entire set of methods JavaScript can access to display information about the SWF as well as control different aspects of the SWF. The following table describes these methods:

Method

Description

 

 

gotoFrame

Sends the SWF to the frame specified in the parameter. The parameter

 

must be a root frame name or root frame number.

getVariable

Returns a root variable with the name specified as a string in the parameter.

IsPlaying

Checks whether the SWF’s root timeline is playing. This method returns a

 

Boolean.

pan

Moves the x and y position of the SWF.

percentLoaded

Returns a number from 0–100 indicating the percentage of the SWF’s

 

bytes loaded.

play

Identical to calling play() on the root timeline.

rewind

Sends the root timeline to frame 1.

setZoomRect

Zooms in on a specified rectangular area of the SWF.

606

 

 

Putting JavaScript to Work

 

 

 

 

Method

Description

 

 

 

 

setVariable

Sets a variable on the root timeline of the SWF.

 

stopPlay

Identical to calling stop() on the root timeline of the SWF.

 

totalFrames

Returns the total frames of the root timeline of the SWF.

 

zoom

Sets the zoom property of the SWF.

The following table describes some of the basic JavaScript Flash events:

Event

Description

 

 

onProgress

Automatically is fired when the percentage of bytes loaded changes.

onReadyStateChange

Fires whenever the state of the SWF changes. The parameter is populated

 

with a numeric code: 0=Loading, 1=Uninitialized, 2=Loaded, 3=Initialized,

 

4=Complete.

fscommand

Fires when you use a URL in an fscommand, and the URL starts with

 

fscommand:’.

Macromedia has documented more events and properties that JavaScript can access. The aforementioned are the basic set that will enable your JavaScript to communicate with your Flash movie. If you need more JavaScript-to-Flash control, consult the Macromedia documentation for the very latest supported properties, methods, and events. Always test your target systems for compliance and functionality.

Using the Flash JavaScript Integration Kit

The Flash JavaScript Integration Kit is a set of JavaScript files and a set of specific ActionScript code within a shim SWF file. The shim is loaded into a separate div, rather than within the main SWF file. This shim acts as a communication point to the JavaScript. An interesting fact is that the Flash JavaScript Integration Kit is really a set of classes and tools that all still use getURL to make its main JavaScript calls.

So why use the Flash Integration Kit? The integration kit neatly organizes the job of bidirectional JavaScript/Flash communication. The integration kit also allows for communication of complex data types between Flash and JavaScript. These can include objects, arrays, Strings, Numbers, Booleans, and more. The Helper classes that come with the kit automatically handle the parsing of the data types, making Flash-to-JavaScript integration seamless and simple. Also, the integration kit is open source and is maintained by the OSFlash organization, a group of folks dedicated to open source Flash initiatives.

You can get the integration kit from Macromedia at http://weblogs.macromedia.com/flash javascript/ or from osflash.org at http://osflash.org/doku.php?id=flashjs. Of course, these URLs are susceptible to linkrot and might change but are working at the time of this writing.

607