Javascript to Flash Communication

Ben and I have been looking into solving a workaround for I18N text input, using a Flash to an HTML form. Why? Because browsers have support for RTL language input. Flash MX 2004 does not. So the idea is to let the browser do the input and then somehow suck the data back into the Flash App, where it can massage the text into a semblence of a correct appearance. A big round trip from Flash to Javascript back to Flash…interesting, yes?

The challenge is to get Flash to open an HTML form with some dynamic text, allow the user to edit that HTML form, and on clicking OK send the text back to Flash. On as many browsers as possible. Ben figured out a ton of stuff over the weekend, and I’m writing it down so I don’t forget.

Our Flash app sends the text to the server using LoadVars.sendAndLoad(). The returned LoadVars object has a URL, generated by the server, that is used to open an HTML page via GetURL("javascript:MyOpenHTMLForm(...)"). The reason for that is so the windows are linked: parent window with SWF has javascript that creates a child window with our HTML form. Otherwise, you can’t get the data back.

The big snag is getting the data back into Flash. Support is spotty for Javascript-to-Flash communication in browsers, but MustardLab posted a universal technique back in 2003 for accomplishing this. You can download the samples, but the documentation is oriented toward using their code, not how it works. It’s incredibly sneaky-cool:

  1. You know how you can pass variables from HTML to FlashPlayer? But you can only do it once? The MustardLab Universal Javascript-to-Flash (or MLJS as I’ll call it from now on) uses this with some Javascript/DHTML techniques to dynamically load a small SWF movie (the “gateway.swf”). It’s like replacing GIFs on the fly for an HTML rollover, except you’re reloading a SWF. And everytime the SWF loads, it gets new FlashVars with values that are dynamically written by the DHTML code.

  2. So you can reload this tiny gateway.swf file, but your variables do no good there! You want to send them back to the MAIN movie! That’s where the Flash inter-SWF communication technique comes in. You can use the LocalConnection class to talk between two different movies on your system, so long as you know what its name is. So the gateway.swf uses this mechanism to talk to the main.swf.

  3. Everything else is just glue. But it’s a lot of glue involving ActionScript, Javascript, and working with the FlashPlayer <object> attributes. Kudos to the MLab guys for working out the basic technique, and wrapping it up on their site.

<

p>Dealing with the non-latin character sets in a way that Flash will digest is a little sticky too, but that’s a topic for another day.