Send/Receive messages from Javascript to Flash

I needed to send and receive messages from javascript to a flash movie built in haXe.

Googling showed references to Haxe's remoting class, but there's a much simpler (and possibly less robust!) way using flash's ExternalInterface class.

First your going to need a reference to your flash movie. If you've embedded it using flashembed (and you are using flashembed, aren't you?), you can do it like this:

var movieObj;

$(document).ready(function() {
	var api = flashembed('background', {src: 'vid.swf', wmode: 'opaque', allowScriptAccess: 'always'});	
	movieObj = document.getElementById(api.getApi().id); 
});

movieObj now contains a reference to the flash movie's DOM element.

We can now send messages to the flash movie like this:

movieObj.pause();

OK, so far so good.

Now we need to tell the flash movie what to do with these messages.

In the flash actionscript, register the message with ExternalInterface, something like this:

import flash.external.ExternalInterface;

class Foo {
    
    public function new(){
        ...
        ExternalInterface.addCallback( 'pause', doPause );        
    }

    function doPause() {
        trace('got pause()');
    }

    public static function main() {
        new Foo();
    }    
    
}

Et voil√°.

Now to get it working the other way around, you can call any javascript function (your own, or a built-in function) like this:

ExternalInterface.call('jsFunctionName', 'argument');   
// eg:
// ExternalInterface.call('alert', 'Foo!');   
  • December 23, 2010
comments powered by Disqus
Back to Top