One of the projects I've been working on does a lot with communication between JavaScript and Flash. The ExternalInterface available in ActionScript 3 makes this a lot easier, and I've been wanting to do something cool with it. For now, I've worked on this example to illustrate the basics of how ExternalInterface works and its simplicity.
The relevant portion of the ActionScript:
// Add an ExternalInterface callback for communication from JavaScript
function flashCallback(data:String):void {
textBox.text = "JavaScript: You clicked " + data + ".";
}
ExternalInterface.addCallback("flashCallback", flashCallback);
// Add listeners to communicate to JavaScript via ExternalInterface
circle.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
ExternalInterface.call("jsObject.callback", "Green Circle");
});
square.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
ExternalInterface.call("jsObject.callback", "Red Square");
});
The relevant portion of the JavaScript:
// Create a JavaScript object containing the callback for communication from Flash and triggers to communicate to Flash
var jsObject = (function() {
var triggers = document.getElementsByTagName('a');
var init = (function() {
YAHOO.util.Event.addListener(triggers, 'click', function(e) {
YAHOO.util.Event.stopEvent(e);
YAHOO.util.Dom.get('mySWF').flashCallback(this.innerHTML);
});
})();
return {
callback: function(data) {
YAHOO.util.Dom.get('flash_response').innerHTML = 'Flash: You clicked the ' + data + '.';
}
}
})();
View source on the example for more details.