HowTo: communicate with flash by Grouch

This post briefly explains possibilities of communication with flash, which can be performed via parameters, variables and methods. Communication can be achieved by implementing necessary scripts in actionscript, javascript and php languages. It bases on flash:ThumbnailCropTool example (soon available in the download section).

ThumbnailCropTool is a tool used for creating custom thumbnails from original images. It may look and work like the following (use each of 4 tools at top left corner of the flash below the images):

You need to upgrade your Flash Player

JavaScript to Flash communication

As you could possibly check in the page source, 6 image thumbnails above the crop tool are inserted into html with standard <img> markup. You could also check or in Firefox see in your status bar after rolling with your mouse over any of the 6 thumbnail images, that every image is inside <a> tag which executes sendData javascript function with a string parameter: number and a path to the original image seperated by the comma. After we click the thumbnail, javascript code executes sendData function with appriopriate parameter. The sendData function communicates with flash object by the SetVariable method, this means, we don’t need additional mechanism other than swfobject 2.0, but we must predict almost every aspect of data exchange procedures. Thumbnail click executes the following code:

// JavaScript
function sendData (param) {
	var obj = document.getElementById("imageCrop");
	if (obj) {
		if ( typeof obj.SetVariable != "undefined" ) {
			obj.SetVariable("JStoASviaSetVariable", param);
		}
	}
}

It sets the JStoASviaSetVariable variable of the _root object in flash element with the value provided by the parameter. We must set name and id attributes of the embeding flash object in order to call SetVariable method, which means we need a reference to the swf object. We do it like this:

// JavaScript
// _domain - used for full-path-linking
var flashvars = { _domain:"http://www.viztoolkit.com/flash/03-09/" };
// connection settings and flash menu trim
var params = { swliveconnect:"true", allowScriptAccess:"sameDomain",
  menu:"false" };
// id / name - used as reference for communication from javascript to flash
var attributes = { id:"imageCrop", name:"imageCrop", bgcolor:"#e1e1e1" };
// swf object 2.0 embed swf
swfobject.embedSWF("imageCrop.swf", "imageCropContent", "652", "450", "9.0.0",
  "expressInstall.swf", flashvars, params, attributes);

Note _domain variable is used for direct linking as a prefix for all links inside of flash object.
It should be rendered into html using php statement:
echo “http://” . $_SERVER['SERVER_NAME'] . “/flash/03-09/”;
for the full compatibility.

Meanwhile, in flash actionscript:

  • we set the JStoASviaSetVariable to its initial value – (empty string)
  • we prepare onSetVariable function body – it will split the parameter passed into 2 values seperated by the comma, first one corresponds to the thumbnail image number, the second one is the relative path to the original image (normally at that case I would use only one parameter, but for the educational purposes…), then it will execute initLoadImage which starts loading picture to the thumbnailCropTool
  • we watch the value of the JStoASviaSetVariable variable for changes
// ActionScript
JStoASviaSetVariable = "";

_root.onSetVariable = function(prop:String, oldval:String, newval:String) {
	var nvs = newval.split(",");
	_root.curNum = Number ( nvs[0] );
	_root.initLoadImage ( nvs[1] );
}

_root.watch("JStoASviaSetVariable", _root.onSetVariable );

Flash to php with response

After we choose thumbnail crop tool crop tool and select the region on the loaded original image, flash sends calculated data (with the region coordinates and image number) to the php service on the server (generateThumbnail.php) using GET method. Earlier, we need to set the onData event for the LoadVars variable – it will be used when response from the server arrives.

Install flash player!

// ActionScript
_root.xload = new LoadVars();
_root.xload.onData = function(src:String) {
	if (src == undefined) {
		trace("Error loading content.");
		return;
	}
	_root.refreshThumbnail ( src.split(",")[0], src.split(",")[1] );
};
_root.xload.load(_root._domain+"generateThumbnail.php?num="+_root.curNum+"&ox="+x1+"&oy="+y1+"&ow="+(x2-x1)+"&oh="+(y2-y1), _root.xload, "GET");

The service generates thumbnail based on coordinates, it generates also the name of the destination file name, so every crop is an individual file on the server. Finally, it echos image number and the generated file name seperated by the comma, so the flash object can load that data:

// php
echo $_GET["num"].',imgs/gen/'.$serverFileName;

Flash to JavaScript communication

In actionscript, when the data from the php service is sent back to the browser, onData event callback splits the data retrieved and executes refreshThumbnail function which executes javascript refreshThumb method with the appriopriate parameters.

// ActionScript
_root.refreshThumbnail = function ( num, path ) {
	getURL("javascript:refreshThumb("+num+",'"+path+"');");
}

Javascript function changes src attribute of the <img> tag to path to the recently generated thumbnail. It is achieved by setting id attribute of every thumbnail <img> tag, so we can find reference to the right image object using getElementById function.

// JavaScript
// callback function for image source switch after thumbnail generation
function refreshThumb ( iid, isrc ) {
	document.getElementById("thmb"+iid).src = isrc;
}

To sum it up, the communication chart looks like the following:

Message chart for flash:ThumbnailCropTool

Hope you’ve found it useful.

GHTime Code(s): 2e1bb 

Leave a comment

Your comment