Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Javascript to Flash communication and vise versa

The communication between Flash and JavaScript is really important part of the web sites today. That's why I decided to share how to do it.

In the example here I made two areas. The left one contains Flash text form and the other one HTML based text area. By clicking on the buttons the text of the boxes is transferred between each other. Here is the HTML code:

<div id="animation"></div>
  <div id="content">
    <h1>HTML AREA (type something in the area below)</h1>
    <textarea id="htmlArea"></textarea>
    <input type="button" id="htmlButton" value="send to flash" />
  </div>
  <script type="text/javascript">
  function onFlashTextChanged(text) {
    document.getElementById("htmlArea").value = text;
  }
  
  function onHTMLTextChanged() {
    document.getElementById("animationSwf").changeText(document.getElementById("htmlArea").value);
  }
  var swf = new FlashObject("swf/flash.swf", "animationSwf", "300", "200", "9", "#CCCCCC");
  window.onload = function() {
    swf.write("animation");
    document.getElementById("htmlButton").onclick = onHTMLTextChanged;
  }
  </script>

The ActionScript code:

package lib.document {
  import flash.display.MovieClip;
  import flash.events.Event;
  import flash.events.MouseEvent;
  import flash.text.TextField;
  import flash.external.ExternalInterface;
  public class App extends MovieClip {
    public
    var field: TextField;
    public
    var button: MovieClip;
    public
    function App() {
      button.mouseChildren = false;
      button.buttonMode = true;
      button.addEventListener(MouseEvent.CLICK, onButtonClick);
      button.addEventListener(MouseEvent.MOUSE_OVER, onButtonOver);
      button.addEventListener(MouseEvent.MOUSE_OUT, onButtonOut);
      ExternalInterface.addCallback("changeText", changeText);
    }
    private
    function onButtonClick(e: Event): void {
      ExternalInterface.call("onFlashTextChanged", field.text);
    }
    private
    function onButtonOver(e: Event): void {
      e.target.alpha = 0.5;
    }
    private
    function onButtonOut(e: Event): void {
      e.target.alpha = 1;
    }
    private
    function changeText(str: String): void {
      field.text = str;
    }
  }
}
If you enjoy this post, share it on Twitter, Facebook or LinkedIn.