JavaScript events in Flash: Now for Mac

Wednesday 6 April 2005  –  Filed under: Flash  –  No Comments

Two weeks ago I posted my ExternalFunction class, which allows you to generate EventDispatcher events in Flash through Javascript. As one of my visitors pointed out, this solution doesn’t work on Safari. So I wrote a different implementation, which also supports Safari on Mac OS X.

This new version is based on the method developed by Mustardlab.com, which uses a gateway.swf to pass Javascript variables to the main Flash application by means of a LocalConnection. This is necessary, as Safari on Mac OS X doesn’t support the setVariable method to, hence its name, set variables in Flash through Javascript. Unfortunately, the Mustardlab implementation sets the value of a variable directly in Flash and doesn’t support events.

I order to support EventDispatcher events in Flash, I have completely rewritten my original ExternalFunction class to support a LocalConnection to receive variables and then broadcast an event, its name being specified by Javascript. I have also upgraded the original gateway.swf to support ActionScript 2.

Like the previous implementation, this allows you to subscribe Flash objects to any JavaScript event you wish to pass to your Flash application by using a regular .addEventListener() call.

In ActionScript:

import ExternalFunction;
import ExternalFunctionEvent;

var mExtFunc:ExternalFunction = ExternalFunction.getInstance();
mExtFunc.addEventListener("onMyEvent", this);

var onMyEvent:Function = function ( e:ExternalFunctionEvent ) {
	// code goes here...
}

In HTML1:

<script language="javascript">
function flashEvent(inSwf, inEvent, inParams) {

	var divcontainer = "flash_setvariables_" + inSwf;
	if(!document.getElementById(divcontainer)){
		var divholder = document.createElement("div");
		divholder.id = divcontainer;
		document.body.appendChild(divholder);
	}
	var divinfo = "<embed src='gateway.swf' FlashVars='lc=" + inSwf + "&ev=" + escape(inEvent) + "," + escape(inParams) + "' width='0' height='0' type='application/x-shockwave-flash'></embed>";
	document.getElementById(divcontainer).innerHTML = "";
	document.getElementById(divcontainer).innerHTML = divinfo;
}
</script>

<a href="javascript:flashEvent('swfname', 'onMyEvent','image_01.jpg');">view image 1</a>

There’s an online example available. Download the source code here. I also wrote some documentation for this class, which can be found here.

1 Please note that you need to carefully name your main Flash application using the ‘id’ parameter in the object tag and also set the same name in the embed tag using the ‘name’ parameter. This id is used as the name of the LocalConnectin to setup and is passed to both the main Flash application and gateway.swf through FlashVars.

Leave a Reply


Recent Articles

Advertisement

Categories