Thursday 10 September 2009

Javascript and ActionScript Converse: Introduction to ExternalInterface

Step 1: The ExternalInterface Class

Where Can I Use it?

Currently the ExternalInterface Class is available in the following browsers:

  • Internet Exlplorer 5.0+
  • Netscape 8.0+
  • Mozilla 1.7.5+
  • Firefox 1.0+
  • Safari 1.3+

What Can I do With it?

The ExternalInterface Class allows you to:

  • Call any Javascript function from ActionScript.
  • Call any ActionScript function from Javascript.
  • Pass arguments and paramters between the two.
  • Receive a return value from a Javascript function.
  • Return a value to a Javascript function.

Step 2: Let's Create Our HTML Page

We'll jump right into this and start with a really basic example. First we need to create our HTML Page, so fire up your favorite HTML Editor and let's start. Create a form inside your HTML.

  1. >
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5. <title>ExternalInterface Test 1title>
  6. head>

  7. <body>
  8. <div id="testArea">
  9. <form name="myForm">
  10. <label for="output">Text from Flashlabel>
  11. <input type="text" id="output" name="output" value="" />
  12. form>
  13. div>
  14. body>
  15. html>

Step 3: SWF Referencing Function

To easily reference the SWF in our HTML, we're going to create a Javascript function so that we can reference the SWF in our code. To accomplish this, place this script between the "head" tags.


This function will return the SWF that is passed as a parameter of the flashMovie() function. For example, "flashMovie('testMovie');" would return the swf with an id of 'testMovie'.

Step 4: Create Function to Receive Values From ActionScript

Now we'll create a Javascript function which accepts a value from ActionScript. Place this inside our already made script tags.

  1. function sendToJS(value)
  2. {
  3. document.forms["myForm"].output.value = value;
  4. }

This will take whichever value we get from the ActionScript and place it in our textfield with an id of "output".

Step 5: Open up Flash

Let's open up Flash and start working on the ActionScript. Create a new ActionScript 3.0 File and create a new Document Class named "EIFace1".

Create new ActionScript 3.0 File.
Create EIFace Document Class

Step 6: Setup the Document Class

I'll be using FDT to write EIFace.as, but you're welcome to use any ActionScript Editor you feel comfortable with. We'll start out by creating a standard Document Class Shell.

  1. package
  2. {
  3. import flash.display.Sprite;
  4. /**
  5. * @author kreativeKING
  6. */
  7. public class EIFace1 extends Sprite
  8. {
  9. public function EIFace1()
  10. {

  11. }
  12. }
  13. }

Step 7: Creating Our TextField

Create the textfield we'll be using to send our values.

  1. field1 = new TextField();
  2. field1.type = TextFieldType.INPUT;
  3. field1.width = 300;
  4. field1.height = 20;
  5. field1.border = true;
  6. field1.borderColor = 0x565656;
  7. field1.background = true;
  8. field1.backgroundColor = 0x121212;
  9. field1.defaultTextFormat = new TextFormat("Arial", 14, 0xEFEFEF);
  10. field1.x = stage.stageWidth * .5 - field1.width *.5;
  11. field1.y = stage.stageHeight * .5- field1.height *.5;
  12. stage.addChild(field1);

Step 8: Create a Send Button

Create a Button to click. I'm not a fan of using components, so I'll be building a button from scratch using Flash IDE. You're welcome to just create a box or use the SimpleButton component; I'll let you use those creative juices. If you need no further help with building a button, you can skip to Step 11.

Start by creating a rectangle with the Rectangle Primitive Tool. I won't provide specific values, just feel it out to asetting you like.

Create a square.

Step 9: Continue the Button Creation

Convert the rectangle into a MovieClip.

Convert to symbol.

Create a New Layer inside the MovieClip and place "Send To JS" text.

Create Text.

Step 10: Export For ActionScript

Go into your library, right-click on the button and Export for ActionScript.

Export For ActionScript.

Step 11: Code in the Button

We're going to code our button into our Document Class.

  1. button1 = new SendButton();
  2. button1.x = stage.stageWidth * .5 - button1.width *.5;
  3. button1.y = field1.y + 30;

  4. stage.addChild(button1);

Step 12: Where Are We Now

This is how your HTML page should now appear.

  1. "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. "http://www.w3.org/1999/xhtml">

  3. "Content-Type" content="text/html; charset=UTF-8" />
  4. ExternalInterface Test 1




  5. "testArea">
  6. "myForm"
    >
  7. "text" id="output" name="output" value="" />




  • The Document Class should look like this.

    1. package
    2. {
    3. import flash.display.MovieClip;
    4. import flash.display.Sprite;
    5. import flash.text.TextField;
    6. import flash.text.TextFieldType;
    7. import flash.text.TextFormat;
    8. /**
    9. * @author kreativeKING
    10. */
    11. public class EIFace1 extends Sprite
    12. {
    13. private var field1 : TextField;
    14. private var button1 : MovieClip;

    15. public function EIFace1()
    16. {
    17. field1 = new TextField();
    18. field1.type = TextFieldType.INPUT;
    19. field1.width = 300;
    20. field1.height = 20;
    21. field1.border = true;
    22. field1.borderColor = 0x565656;
    23. field1.background = true;
    24. field1.backgroundColor = 0x121212;
    25. field1.defaultTextFormat = new TextFormat("Arial", 14, 0xEFEFEF);
    26. field1.x = stage.stageWidth * .5 - field1.width *.5;
    27. field1.y = stage.stageHeight * .5- field1.height *.5;

    28. stage.addChild(field1);

    29. button1 = new SendButton();
    30. button1.x = stage.stageWidth * .5 - button1.width *.5;
    31. button1.y = field1.y + 30;

    32. stage.addChild(button1);
    33. }
    34. }
    35. }

    Step 13: Create ActionScript to Javascript Function

    We now need to create the function that sends the data from Flash to Javascript. This will be a simple function which sends a string.

    1. button1.addEventListener(MouseEvent.CLICK, sendToJS);
    2. private function sendToJS(e : MouseEvent) : void
    3. {
    4. if(ExternalInterface.available)
    5. {
    6. ExternalInterface.call("fromAS", field1.text);
    7. }
    8. }

    We first add an event listener to our button, inside our Document Classes constructor. Then we create our listener. The ExternalInterface.available property checks to see if our browser is able to use the ExternalInterface Class. This isn't necessary to use as we know our browser can support it, but it's good practice for developing for the web and we're never sure if the client browser is going to becompatible.

    The ExternalInterface.call() function is what we use to call our Javascript function. The first parameter is the name of the Javascript function we want to call. It's the name of our function in Javascript as a string. The second parameter is the value we want to pass to the Javascript function. In this case, we're passing the value of our textfield.

    Note: You can pass as many parameters as you want, but the first parameter needs to be the name of the Javascript function.

    Step 14: Testing Time

    Before we can test, we first have to embed our SWF into the HTML. I must stress that it's best to use SWFObject and not the default method that Flash uses to embed SWF files. Let's publish our SWF, setup SWFObject and embed our file.

    Publish the SWF.

    Here's the SWFObject Embed code which goes into the head of the HTML file:



    It's also important that you give the SWF an id. This is important with using the ExternalInterface and for us to target it using the Javascript function we created earlier. Let's create our div that will house the SWF file.

    1. <div id="flashDiv">
    2. <p>This will get replaced with a SWF. If not you need to update your Flash Player.p>
    3. div>

    Here are the Document Class and HTML file up to this point:

    1. package
    2. {
    3. import flash.external.ExternalInterface;
    4. import flash.events.MouseEvent;
    5. import flash.display.MovieClip;
    6. import flash.display.Sprite;
    7. import flash.text.TextField;
    8. import flash.text.TextFieldType;
    9. import flash.text.TextFormat;
    10. /**
    11. * @author kreativeKING
    12. */
    13. public class EIFace1 extends Sprite
    14. {
    15. private var field1 : TextField;
    16. private var button1 : MovieClip;

    17. public function EIFace1()
    18. {
    19. field1 = new TextField();
    20. field1.type = TextFieldType.INPUT;
    21. field1.width = 300;
    22. field1.height = 20;
    23. field1.border = true;
    24. field1.borderColor = 0x565656;
    25. field1.background = true;
    26. field1.backgroundColor = 0x121212;
    27. field1.defaultTextFormat = new TextFormat("Arial", 14, 0xEFEFEF);
    28. field1.x = stage.stageWidth * .5 - field1.width *.5;
    29. field1.y = stage.stageHeight * .5- field1.height *.5;

    30. stage.addChild(field1);

    31. button1 = new SendButton();
    32. button1.x = stage.stageWidth * .5 - button1.width *.5;
    33. button1.y = field1.y + 30;

    34. stage.addChild(button1);

    35. button1.addEventListener(MouseEvent.CLICK, sendToJS);
    36. }

    37. private function sendToJS(e : MouseEvent) : void
    38. {
    39. if(ExternalInterface.available)
    40. {
    41. ExternalInterface.call("fromAS", field1.text);
    42. }
    43. }
    44. }
    45. }
    1. >
    2. <html xmlns="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    5. <title>ExternalInterface Test 1title>
    6. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js">script>
    7. <script type="text/javascript">
    8. var flashvars = {};
    9. var params = {};
    10. params.allowscriptaccess = "always";
    11. params.allownetworking = "all";
    12. var attributes = {};
    13. attributes.id = "EIFace";
    14. swfobject.embedSWF("EIFace.swf", "flashDiv", "350", "200", "9.0.0", false, flashvars, params, attributes);
    15. script>
    16. <script type="text/javascript">
    17. function flashMovie(movieName)
    18. {
    19. if(window.document[movieName])
    20. {
    21. return window.document[movieName];
    22. }
    23. else
    24. {
    25. return document.getElementById(movieName);
    26. }

    27. }

    28. function fromAS(value)
    29. {
    30. document.forms["myForm"].output.value = value;
    31. }
    32. script>
    33. head>

    34. <body>
    35. <div id="flashDiv">
    36. <p>This will get replaced with a SWF. If not you need to update your Flash Player.p>
    37. div>
    38. <div id="testArea">
    39. <form name="myForm">
    40. <label for="output">Text from Flashlabel>
    41. <input type="text" id="output" name="output" value="" />
    42. form>
    43. div>
    44. body>
    45. html>

    Now open up your HTML wrapper and test it out. You'll see that the value of the textfield in flash becomes the value on the textfield in our HTML. At a glance, the code behind this is pretty simple and straight forward. Now let's try sending some information from Javascript to ActionScript.

    Step 15: Make Additional Fields

    We're going to create additional fields to send information from Javascript to ActionScript.

    1. <label for="input">Send Text To Flashlabel>
    2. <input type="text" id="input" name="input" value="" />
    3. <input type="button" value="SendToFlash" onClick="sendToFlash(myForm.input.value);" />
    1. field2 = new TextField();
    2. field2.type = TextFieldType.DYNAMIC;
    3. field2.width = 300;
    4. field2.height = 20;
    5. field2.border = true;
    6. field2.borderColor = 0x565656;
    7. field2.background = true;
    8. field2.backgroundColor = 0xEFEFEF;
    9. field2.defaultTextFormat = new TextFormat("Arial", 14, 0x121212);
    10. field2.x = stage.stageWidth * .5 - field2.width *.5;
    11. field2.y = field1.y - 50;

    12. stage.addChild(field2);

    Step 16: Create The Javascript to ActionScript Function

    We need to create a function which sends the value from inside our HTML to Flash. This is similar to the function we created to send values from ActionScript to Javascript.

    1. function sendToFlash(value)
    2. {
    3. flashMovie("EIFace").sendToFlash(value);
    4. }

    We use the function we created earlier to reference the embedded SWF. Now we must go into our Document Class and set up Flash to receive values from Javascript and create a new function that Javascript will be calling.

    Step 17: Adding Callbacks

    To register Javascript functions, we need to add callbacks so that Flash knows what we're trying to send when we call an ActionScript function. Let's finally start calling some ActionScript.

    1. private function addCallbacks() : void
    2. {
    3. if(ExternalInterface.available)
    4. {
    5. ExternalInterface.addCallback("sendToFlash", fromJS);
    6. }
    7. }

    The ExternalInterface.addCallback() function registers a function in ActionScript to be called by Javascript. The first parameter is the function name by which Javascript will know the function. The second parameter is the actual function.

    Simply put, that means in our Javascript, we would call sendToFlash() and that would invoke the fromJS() function in ActionScript.

    Step 18: Creating fromJS()

    Now we're going to create the fromJS() function. This is a very simple function that will assign the value passed to it to the text field.

    1. private function fromJS(value:String) : void
    2. {
    3. field2.text = value;
    4. }

    Time for another test and see what we come up with. Here's what the Document Class and HTML look like now:

    1. package
    2. {
    3. import flash.external.ExternalInterface;
    4. import flash.events.MouseEvent;
    5. import flash.display.MovieClip;
    6. import flash.display.Sprite;
    7. import flash.text.TextField;
    8. import flash.text.TextFieldType;
    9. import flash.text.TextFormat;
    10. /**
    11. * @author kreativeKING
    12. */
    13. public class EIFace1 extends Sprite
    14. {
    15. private var field1 : TextField;
    16. private var button1 : MovieClip;
    17. private var field2 : TextField;

    18. public function EIFace1()
    19. {
    20. field1 = new TextField();
    21. field1.type = TextFieldType.INPUT;
    22. field1.width = 300;
    23. field1.height = 20;
    24. field1.border = true;
    25. field1.borderColor = 0x565656;
    26. field1.background = true;
    27. field1.backgroundColor = 0x121212;
    28. field1.defaultTextFormat = new TextFormat("Arial", 14, 0xEFEFEF);
    29. field1.x = stage.stageWidth * .5 - field1.width *.5;
    30. field1.y = stage.stageHeight * .5- field1.height *.5;

    31. stage.addChild(field1);

    32. field2 = new TextField();
    33. field2.type = TextFieldType.DYNAMIC;
    34. field2.width = 300;
    35. field2.height = 20;
    36. field2.border = true;
    37. field2.borderColor = 0x565656;
    38. field2.background = true;
    39. field2.backgroundColor = 0xEFEFEF;
    40. field2.defaultTextFormat = new TextFormat("Arial", 14, 0x121212);
    41. field2.x = stage.stageWidth * .5 - field2.width *.5;
    42. field2.y = field1.y - 50;

    43. stage.addChild(field2);

    44. button1 = new SendButton();
    45. button1.x = stage.stageWidth * .5 - button1.width *.5;
    46. button1.y = field1.y + 30;

    47. stage.addChild(button1);

    48. button1.addEventListener(MouseEvent.CLICK, sendToJS);
    49. addCallbacks();
    50. }

    51. private function addCallbacks() : void
    52. {
    53. if(ExternalInterface.available)
    54. {
    55. ExternalInterface.addCallback("sendToFlash", fromJS);
    56. }
    57. }

    58. private function fromJS(value:String) : void
    59. {
    60. field2.text = value;
    61. }

    62. private function sendToJS(e : MouseEvent) : void
    63. {
    64. if(ExternalInterface.available)
    65. {
    66. ExternalInterface.call("fromAS", field1.text);
    67. }
    68. }
    69. }
    70. }
    1. "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    2. "http://www.w3.org/1999/xhtml">

    3. "Content-Type" content="text/html; charset=UTF-8" />
    4. ExternalInterface Test 1






    5. "flashDiv">
    6. This will get replaced with a SWF. If not you need to update your Flash Player.


  • "testArea">
  • "myForm"
    >
  • "text" id="input" name="input" value="" />
  • "button" value="SendToFlash" onClick="sendToFlash(myForm.input.value);" />


  • "text" id="output" name="output" value="" />




  • Step 19: Results

    As you can see, placing text in our newest field and hitting send sends the value into the Flash text field. Using the ExternalInterface class is very simple and can often come in handy when creating API's and applications that can be manipulated outside of the Flash Movie. For example, this can be implemented in Video Player API's for creating and controlling the video with Javascript.

    Step 20: Who Uses Classic Javascript Anymore?

    For most of the people out there now, no one is really using classic Javascript; jQuery is the wave of the future. Here's an example of using jQuery instead of classic Javascript.


    Here's the new and updated HTML for use with jQuery:

    1. "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    2. "http://www.w3.org/1999/xhtml">

    3. "Content-Type" content="text/html; charset=UTF-8" />
    4. ExternalInterface Test 1







    5. "flashDiv">
    6. This will get replaced with a SWF. If not you need to update your Flash Player.


  • "testArea">
  • "myForm"
    >
  • "text" id="input" name="input" value="" />
  • "button" id="sendToFlash" value="SendToFlash" />


  • "text" id="output" name="output" value="" />




  • Conclusion

    Hopefully you now have a better grasp on using the ExternalInterface Class. If you have any questions or ideas of what else you would like to learn, just leave a comment or tweet me and I'll see what I can do. I hope you learned the concepts and start using them in your own projects. Thanks for reading!

    kreativeKING

    source from : flash tuts+

    0 nhận xét:

    Post a Comment

     

    Blogroll

    Site Info

    Text

    Tut - Designer Copyright © 2009 WoodMag is Designed by Ipietoon for Free Blogger Template