FacebookTwitterGoogle+Share

Using ExternalInterface to communicate between Javascript and Actionscript 3: Or, I want Paypal buy now buttons in Flash

The statement that Flash TextAreas ( TextFields, etc. ) can display HTML can be deceptive. They can certainly display a subset of HTML. But this is a very limited subset, and for good reason.

While it’s easy to understand why this is the case, it can still be frustrating.

Say, for example, you’re building an image gallery and would like to have some of Paypal’s buy-now buttons in the image descriptions. A Paypal button can be perhaps a deceptive thing — it’s a tiny form, whose only visible element is the buy-now image — which cannot easily be accurately displayed by Flash.

But don’t worry, especially if your Flash will be displayed within a browser, for that is a thing built to display HTML. It’s one of its primary and most useful purposes.

The trick here is to get Flash to communicate to the browser what HTML to display, and how to do it. It turns out this is relatively easy to accomplish.

Here we make the following assumption: Your SWF file knows what HTML to display, and when.

Okay, so I’ll break the method down into steps:

  1. 1: Flash tells javascript to display some HTML.

Okay that’s about it.

You’ll have to write the Javascript to display the HTML where you want it, but that’s easy enough.

Flash provides an External Interface class ( flash.external.ExternalInterface ) which allows for communication between Actionscript 3 and the Flash Player container — in this case the web page and its Javascript.

You’ll have to include the ExternalInterface in your class file, and there are some checks you can (and probably should) diligently perform, but the important Actionscript 3 is:

import flash.external.ExternalInterface;
...
var html:String = "<p>This is some html.</p>";
if (ExternalInterface.available) {
	ExternalInterface.call("writeHTML", html );
}

The Javascript function writeHTML() will be called with the parameter html. So it’d probably be good if there was such a function:

function writeHTML( str ) {
	document.write( str );
}

A better Javascript function would be, well.. better.. but, you know, brevity and all that.

That’s basically all there is to it. Next time I’ll provide a more concrete example of ExternalInterface in use (one that uses multiple parameters in its Javascript call). And if you want, post the applicable code.

As a side note: if you’re loading the HTML via XML, always remember to wrap it in CDATA.

 

Comments

You must be logged in to post a comment.