Calling Flash AS3 functions from Javascript

Well, I spent all day figuring this one out, so I thought I would share it for everyone to learn from my mistakes. Basically, for this I used Adobe’s ExternalInterface about which Adobe says in the documentation “Adobe recommends using ExternalInterface for all JavaScript-ActionScript communication.” So once I saw that, I knew it had to be possible. Ok, enough with the intro, here’s my code. I will explain below.

Flash Actionscript:

import flash.external.ExternalInterface;
ExternalInterface.addCallback("sendTextToFlash", getTextFromJavaScript);
function getTextFromJavaScript(str):void {

That’s it! All you need to know is that “sendTextToFlash” is the name of the Javascript function Flash is listening for, and then it calls “getTextFromJavaScript” once it hears the call. “str” is the variable that is passed to Flash from the Javascript.

HTML/Javascript (don’t worry, it’s simple):

<script type="text/javascript">
	var currentPage="Home";
	function setCurrentPage(newPage) {
		currentPage = newPage;

This bit is called when the user clicks on a link in the page, which looks like this:

<a href="javascript:void(0);" onClick="setCurrentPage('Home')">Home</a>

And in turn, it calls “SendDataToFlashMovie” Now, back to the Javascript (For those of you unfamiliar with HTML and Javascript, please read a bit on the two before reading on. Otherwise I may confuse you).

function getFlashMovieObject(movieName){
	if (window.document[movieName]){
		return window.document[movieName];
	if (navigator.appName.indexOf("Microsoft Internet")==-1){
		if (document.embeds &amp;&amp; document.embeds[movieName])
			return document.embeds[movieName];
		return document.getElementById(movieName);

The above function is for handling all the lovely browsers and their rendering engines. It should make this setup work on both Windows and Mac. You shouldn’t need to change much there.

function SendDataToFlashMovie(newPage){
	var flashMovie=getFlashMovieObject("main_flash");

Here is where the magic happens. The flashMovie is set by the function above it. “main_flash” should be changed to the name of your flash embed id. I recommend usingĀ swfobject to embed your swf.