Saturday, 1 September 2012

Call Javascript function from Actionscript 3

In this quick tip I will use the ExternalInterface class to call a Javascript function using Actionscript 3. The ExternalInterface class enables communication between Actionscript and the SWF file within a HTML page. The call() method is used to call a Javascript function from Actionscript. Below is a simple example. I have three buttons on the stage. When a button is clicked the ExternalInterface.call() method is called passing the Javascript function and the optional argument. Each button passes a different argument. Note that you can pass any number of arguments and pass different data types.

Security.allowDomain("*");

button1.addEventListener(MouseEvent.CLICK, clicked);
button2.addEventListener(MouseEvent.CLICK, clicked);
button3.addEventListener(MouseEvent.CLICK, clicked);

function clicked(e:MouseEvent):void
{
 if (ExternalInterface.available) 
 {
  if(e.target.name == ‘button1’) ExternalInterface.call("callJSFunc", 1);
  if(e.target.name == ‘button2’) ExternalInterface.call("callJSFunc", 2);
  if(e.target.name == ‘button3’) ExternalInterface.call("callJSFunc", 3);
 }
}

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Call Javascript function from Actionscipt</title>
 <script src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
</head>
<body>
 
 <div id="flashContent"></div>
 
 <script>
  var flashvars ={};
  var params = {allowscriptaccess:"always"}; 
  var attributes = {};
  
  swfobject.embedSWF("calljavascript.swf", "flashContent", "550", "400", "10", false, flashvars, params, attributes);
  
  function callJSFunc(num)
  {
   console.log('The passed number is: ', num);
  }
 </script>
 
</body>
</html>

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP