Share Coding

Tutorials, Problems, Stuffs …

jQuery Call Flash or Flash Call JavaScript

Click here for Demo

This time we need jQuery library and two plugins: EXTERNALINTERFACE and swfObject

<script type="text/javascript" src="http://www.davecomeau.net/javascript/jquery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://www.davecomeau.net/javascript/jquery/jquery.externalinterface.js"></script>
<script type="text/javascript" src="http://www.davecomeau.net/javascript/swfobject/swfobject.js"></script>

For example, I am going to control Flash to play different MovieClips by given parameter: lang
Below is the coding of creating a swfobject, you do NOT need to use <object> or <embed>.

<script type="text/javascript">
	$(document).ready(function() {
		var flashvars = { lang: "zh" };
 // var doublevars = { lang:"zh", ver2:"haha" };
		swfobject.embedSWF('movie.swf', 'flashMovieDiv', '480', '320', '10.0.0', "http://get.adobe.com/tw/flashplayer/", flashvars);
	});
</script>
  • movie.swf – SWF file path
  • flashMovieDiv – The target <div> to place the swfobject
  • 480, 320 – The size of swfObject
  • 10.0.0 – Flash version detect
  • flashvars – The parameters

After that I made a button to call function inside the Flash

$( '#btnAdvR' ).button().click(function(){
	$('#flashMovie').externalInterface({
		method:'flashMethodToCall',
		args: "Hello",
		success: function(response) { // When method has been found in the SWF
			alert('return: ' + response);
		},
		error: function(error) { // When flash method not found
			alert('error: ' + error);
		}
	});
});

You need to include this to your FLV. This is movie.swf

import flash.external.ExternalInterface;

ExternalInterface.addCallback("flashMethodToCall", theFunctionToCall);

var lang:String = "";
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (var keyStr in paramObj) {
	lang = String(paramObj[keyStr]); // A parameter is stored at lang, you may store many parameters by lang:Array
}

function theFunctionToCall(args = null):Boolean { // Do not change it to args:String
	if (...) {
		return true;
	} else {
		return false;
	}
}

To call JavaScript function from flash, only two sentence:

import flash.external.ExternalInterface;

ExternalInterface.call("jsFunction", rmsg);

jsFunction is javascript function name and rmsg is parameter.

<script>

function jsFunction(rmsg){

// I should not place in a jQuery area or will have no result

}

</script>

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: