Tahir’s Blog

Blog about latest technology trends and thing I find interesting.

September-5-07

Communication between JavaScript and Flash

posted by Tahir Khan

Communication between JavaScript and Flash’s ActionScript is a very useful feature. It has a lot of potential and possibilities are unlimited. Although you can use Canvas, VML and SVG controls from JavaScript, Flash can be another alternative. Not only you can use flash for image manipulation and graphics, it also allows video’s, MP3 and many other powerful controls.

Few possibilities are drawing controls, xml request, socket connections, MP3 controls, video control. You can use flash’s movie panel to instantly draw great charts in vector format with great amount of user interaction. Also you can use flash to act as proxy without an actual proxy script or redirects, to read more on the subject, check out the post “Flash as AJAX proxy”.

JavaScript and Flash can talk to each other asynchronously with each other. The communication bridge between the two is very basic. JavaScript can talk to Flash by updating ActionScript variables using “SetVariable” method, which is available from “EMBED” tag’s DOM object. Flash can talk to JavaScript by calling “getURL” function available in ActionScript to update the url field of the browser window which the Flash file is being called from.

Example call from JavaScript:

[js]
window.document[”YourFlashMovieReferenceName”].SetVariable(”YourVariableName”,”YourVariableValue”);
[/js]

Example call from ActionScript

[as]
getURL(”javascript:functionName(parameters)”);
[/as]

Because JavaScript can update the variable value in flash, you would need to use a feature in Flash called “watch“. This “watch” function takes two arguments. 1st argument is the name of the variable that flash will keep track of, 2nd argument is the actual function / method which is will get called any time the variable changes. When the function / method gets executed, it gets passed three arguments, 1st argument is the variable name, 2nd argument is the current value of the variable, 3rd argument is the new value which will be updated as the value of the variable after the method is finished executing.

Here is simple tutorial which should help understanding Flash and JavaScript communications little better.

Note: In this example we will create the following files “myMovie.html”, “myMovie.swf” and “myMovie.fla”. These files are also available in this zip file -> jsFlashExample.zip

  • [figure 1] Launch Macromedia Flash and create a new document.

  • [figure 2] For this example lets set the dimensions for the flash movie to be width of 450 pixels and height of 100 pixels.

  • [figure 3] Then using the tool bar, click on the “Text Tool” and add a text object to the stage by clicking on the stage when “Text Tool” is selected. Make sure “Properties” panel is visible, if its not visible then go to “Window” menu on the menu bar and select “Properties”. For the purpose of our demonstration we are using this text field to display the value of our progress. Make sure in properties dialog, you have this text object selected as “Dynamic Text” and put “displayText” as the value in “Var” field. By assigning to a “Var” (short for variable), this text field will now show the value of the variable called “displayText”, which we will define later. Check width and height and make sure they are set to a reasonable number so we have enough room. Also make sure x and y coordinates are set to a value so that the text object is placed on the stage, you wont see the results if the text object is off the stage.

  • [figure 4] Create a new layer in your movie, we will add the ActionScript on this new layer.

  • [figure 5] Make sure “Actions” panel is visible, if its not visible then go to “Window” menu on the menu bar and select “Development Panels” and then select “Actions”.

  • [figure 5X] Click on the first frame on the new layer and make add the following ActionScript code in the Actions panel.

    [as]
    /* Initiate variable “displayText” and set a default value to “Hello world” */
    var displayText = “Hello world”;
    /* Initiate variable “javaScriptCommunicator”, this variable will be updated by JavaScript */
    var javaScriptCommunicator = “”;
    /* add a “watch” feature on the variable “javaScriptCommunicator” and monitor any changes to the variable. */
    _root.watch(
    ‘javaScriptCommunicator’,
    function (id, old_value, new_value){
    /* update variable “displayText” so has the new value of “javaScriptCommunicator” */
    _root.displayText=new_value;
    /* create a temporary variable called “message” this variable will be used a notification which we will send to JavaScript to test communication from Flash to JavaScript */
    var message = “‘”+id+”‘ has changed from ‘”+old_value+”‘ to ‘”+new_value+”‘”;
    /* call a function / method called “talk2JavaScript” with two text parameter, 1 a static value of “flashCommunicator” and second is the variable “message” which contains some message regarding the status of “javaScriptCommunicator” variable. */
    _root.talk2JavaScript(”flashCommunicator”,message);
    /* return the new value so the variable “javaScriptCommunicator” can be updated. If you choose to return some thing else, then that will be set as the new value of “javaScriptCommunicator” variable. */
    return new_value;
    }
    );

    /* Define a function / method called “talk2JavaScript”, this will call the “getURL” which is built into flash, so flash can access the url of your browser and “getURL” set the url bar with the value which is passed in. */
    function talk2JavaScript(functionName,parameterValue) {
    /* while calling “getURL” call “searchAndReplace” function / method to escape any single quotes in the value */
    /* NOTE: getURL is commented out, since we first want to test the communication between JavaScript to Flash, we will uncomment it when testing the communication from Flash to JavaScript. */
    // getURL(’javascript:’+functionName+’(”‘+searchAndReplace(parameterValue,”‘”,”\’”)+’”)’);
    }
    /* Define a function / method called “searchAndReplace”, this will do a simple search and replace by using split and join methods in flash. */
    function searchAndReplace(originalString, searchString, replacementString) {
    var temporaryArray = originalString.split(searchString);
    originalString = temporaryArray.join(replacementString);
    return (originalString);
    }
    [/as]

  • Save your file on your local machine as “myMovie.fla”.

  • [figure 6] To include this flash file in the browser you must export this movie as SWF. To do this go to “File” from menu bar, and select “Export” and then select “Export Movie”

  • [figure 7] Save the movie as “myMovie.swf”

  • Using a text editor of your choice, create a file called “myMovie.html” and save it in the same directory where “myMovie.swf” is saved. Update “myMovie.html” so it has the following content and save the file:

    [html]




    src="myMovie.swf"
    quality="high"
    bgcolor="#ffffff"
    width="450"
    height="100"
    name="myMovie"
    align="middle"
    allowScriptAccess="sameDomain"
    type="application/x-shockwave-flash"
    pluginspage="http://www.macromedia.com/go/getflashplayer"
    />

    Does this really work?

    Ofcouse it does!



    [/html]

  • This example html is simple.

    It has the “embed” tag which calls our flash movie called “myMovie.swf” and we have a attribute called “name” whose value is set to “myMovie”. By doing this we have created a object called “myMovie” which is available in DOM (Document Object Model) of this document and thus it is available to JavaScript as object.

    Also in the HTML we have two JavaScript functions / method.

    1st function / method is called “talk2SWF”. This is the core of JavaScript talking to flash and it takes a text argument “inputValue”. The function uses our object called “myMovie” and call a function / method “SetVariable” on the object and passes in two arguments. First argument is the name of the variable to update, in our case its “javaScriptCommunicator” which is defined in our flash file, and second argument is the value of which was passed in as “inputValue” to “talk2SWF”.

    2nd function / method is called “flashCommunicator” and it is what Flash will use to communicate from Flash to JavaScript. This function just simply takes the incoming argument and displays its value in the alert box.

  • To see the communication from JavaScript to Flash, lets try the following:

    [figure 8] Using a web browser open “myMovie.html”. You will notice it says “Hello world” on the screen which is coming from the swf file included on the page. Because our text object displays the value of “displayText” variable, it will display its initial value of “Hello world”.

    [figure 9] Click on the link “Does this really works?” and you should see the flash content get updated with “Does this really works?”.

  • To see the communication from Flash to JavaScript, lets try the following:

    Open “myMovie.fla” and update the action script.

    From:

    [as]
    // getURL(’javascript:’+functionName+’(”‘+searchAndReplace(parameterValue,”‘”,”\’”)+’”)’);
    [/as]

    To:

    [as]
    getURL(’javascript:’+functionName+’(”‘+searchAndReplace(parameterValue,”‘”,”\’”)+’”)’);
    [/as]

    Then export the swf as “myMovie.swf”.

  • To see the communication from JavaScript to Flash, lets try the following:

    [figure 8] Using a web browser open “myMovie.html”. You will notice it says “Hello world” on the screen which is coming from the swf file included on the page. Because our text object displays the value of “displayText” variable, it will display its initial value of “Hello world”.

    [figure 10] Click on the link “Does this really works?” and you should see the flash content get updated with “Does this really works?”. Also you should see a alert box which says “‘javaScriptCommunicator’ has changed from ” to ‘Does this really work?’” This message content was generated by Flash and was sent from Flash to JavaScript and then JavaScript displayed the message using the “alert” function / method mentioned in “flashCommunicator” function / method.

Tags:
  1. Lara Heacock Said,

    Tahir -

    Your blog is impressive! Do you have any advice for finding folks experienced with Flex? Any suggestions are greatly appreciated.

    Thanks,
    Lara Heacock

Add A Comment