Trigger Javascript functions from Flash AS3

Using the ExternalInterface in AS3 it’s never been easier to trigger Javascript functions on your page that holds your swf.
Previously with AS2 and below We would have used the getURL(“javascript:yourFunction();”) or
fscommand(“messagebox”, “Message box called from within Flash.”)

I was asked on the forums today how this would be done in AS3.

After quickly looking up ExternalInterface in the flash Doc’s I was able to through together a quick working example.
A working example can be seen here.

Here is the code:

// import classes we need
  1. import flash.external.*;
  2. import*;
  3. //Make sure buttons show mouse over
  4. but1.buttonMode=true;
  5. but2.buttonMode=true;
  6. but3.buttonMode=true;
  7. //Added mouse event to buttons
  8. but1.addEventListener(MouseEvent.MOUSE_DOWN,triggerJavascript,false,0,true);
  9. but2.addEventListener(MouseEvent.MOUSE_DOWN,triggerJavascript,false,0,true);
  10. but3.addEventListener(MouseEvent.MOUSE_DOWN,triggerJavascript,false,0,true);
  12. //Function to be triggered by mouse event
  13. function triggerJavascript(e:Event) {
  14. //check name of button pressed
  15. switch ( {
  16. case "but1" :
  17. //open url in fixed size popup
  18."openPopup", "");
  19. break;
  20. case "but2" :
  21. //open url in new window
  22."openURL", "");
  23. break;
  24. case "but3" :
  25. //trigger javascript alert box
  26."triggerAlert", "Alert was triggered from Flash");
  27. break;
  28. }
  29. }
This entry was posted in Flash AS3, html and tagged , , , , . Bookmark the permalink.