How do we call JavaScript from Flex?

The ExternalInterface API makes it very simple to call methods in the enclosing wrapper. We use the static call() method, which has the following signature:
flash.external.ExternalInterface.call(function_name:
String[, arg1, ...]):Object;
The function_name is the name of the function in the HTML page’s JavaScript. The arguments are the arguments that we pass to the JavaScript function. We can pass one or more arguments in the traditional way of separating them with commas, or we can pass an object that is deserialized by the browser. The arguments are optional.
The following example script block calls the JavaScript f() function in the enclosing wrapper by using the call() method:




import flash.external.*;

public function callWrapper():void {
var f:String = "changeDocumentTitle";
var m:String = ExternalInterface.call(f,"New Title");
trace(m);
}



On our HTML page, we define a function as we would any other JavaScript function. We can return a value, as the following example shows:

This feature requires that the embedded movie file have an id attribute. Without it, no call from our Flex application will succeed.
The call() method accepts zero or more arguments, which can be ActionScript types. Flex serializes the ActionScript types as JavaScript numbers and strings. If we pass an objct, we can access the properties of that deserialized object in the JavaScript, as the following example shows:

public function callWrapper():void {
var o:Object = new Object();
o.lname = "Danger";
o.fname = "Nick";
var f:String = "sendComplexDataTypes";
ExternalInterface.call(f,o);
}

Flex only serializes public, nonstatic variables and read-write properties of ActionScript objects. We can pass numbers and strings as properties on objects, simple objects such as primitive types and arrays, or arrays of simple objects.
The JavaScript code can then access properties of the object, as the following example shows:

We can also embed objects within objects, as the following example shows. Add the following code in our Flex application’s block:

public function callWrapper():void {
var f:String = "sendComplexDataTypes";
var o:Object = new Object();
o.lname = "Danger";
o.fname = "Nick";
o.b = new Array("DdW","E&T","LotR:TS");
var m:String = ExternalInterface.call(f,o);
}

The code triggers the following JavaScript in the wrapper:

Flex and Flash Player have strict security in place to prevent cross-site scripting. By default, we cannot call script on an HTML page if the HTML page is not in the same domain as the Flex application. However, we can expand the sources from which scripts can be called.
We cannot pass objects or arrays that contain circular references. For example, we cannot pass the following object:
var obj = new Object();
obj.prop = obj; // Circular reference.
Circular references cause infinite loops in both ActionScript and JavaScript.

No comments:

Post a Comment