Thursday, November 19, 2009

AS3 ExternalInterface | How to use ExternalInterface in AS3 | javascript to call function in flash using ExternalInterface

With ExternalInterface function in AS3, we can call javascript functions that are outside flash and vice versa.


code (flash):


//we can set a callback to our function in flash to enable javascript function to call it
if (ExternalInterface.available) {
ExternalInterface.addCallback("send_from_external", send_from_external);
}
function send_from_external(newText) {
trace(newText);
}

//to call a javascript function from flash
if (ExternalInterface.available) {
ExternalInterface.call("updateMsg", "your string");
}


code (html):

<script language="JavaScript">
function getFlashId(idIe, idMoz) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? idIe : idMoz;
}
function send_message() {
$("#txt_area").attr("disabled", "disabled");
getFlashMovie(getFlashId("swfObject", "swfEmbed")).send_from_external("test_string"); //trigger function inside flash
}
function updateMsg(string) {
alert(string); //from flash
}
</script>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="swfObject"
width="1"
height="1"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
<param name="movie" value="test.swf" />
<param name="quality" value="low" />
<param name="allowScriptAccess" value="always" />
<param name="flashVars" value="" />
<embed id="swfEmbed"
src="test.swf"
quality="low"
width="1"
height="1"
name="ExternalInterfaceExample"
align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="always"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer"
flashVars="">
</embed>
</object>

No comments: