Understanding ExternalInterface in Flash 8

What is ExternalInterface?

ExternalInterface (flash.external.ExternalInterface) is a set of API which lets you communicate seamlessly between ActionScript and the Flash Player container. The container can be a HTML page containing some JavaScript functions, a Visual Basic or VC++ wrapper or a 3rd party desktop application which has Flash player embedded in it. The concept is very similar to using fscommand to communicate with JavaScript but ExternalInterface is more flexible and powerful than fscommand. With ExternalInterface you can call a JavaScript function from Flash and send any number of arguments in most of the data types like Boolean, String, Numbers etc., and the JavaScript function can send data back to Flash and is received by Flash almost immediately.

For a matrix of Browser - OS support look at the table in the livedocs here.

Properties & Methods in ExternalInterface Class

Properties :

public static available : Boolean [read-only]

Usage:
var isAvailable:Boolean = ExternalInterface.available;

Methods:

public static addCallback(methodName:String, instance:Object, method:Function) : Boolean

Usage:

ExternalInterface.addCallback(”flAlert”, null, showAlert);

In this case flAlert is not the actual function which is written inside Flash but a friendly name which the JavaScript or the host application can call to invoke the actual function ( in this case showAlert) which is written in Flash.

**Note** : This method returns a Boolean value of true if the call was successful and false if it fails. The reason for failure may be due to a non-existent function, a security sandbox restriction or some other error. The LiveDocs page for ExternalInterface has some comments to the problem people are facing with and some answers to them.

public static call(methodName:String, [parameter1:Object]) : Object

This method is used to call a function defined in the host application.

Usage:

ExternalInterface.call(”jsAlert”, “Welcome”);

This method returns an Object which is the response received from the host application.

To summarize addCallback method is used to communicate FROM the host application TO flash and the call method is used to communicate FROM flash TO the host communication.

You can see a simple example here.

Download the example files here.

The FLA file has extensive inline comments to understand what is going on. If you still have doubts leave a comment and I will answer.

Related readings:

ExternalInterface (flash.external.ExternalInterface)
Simplecart and External Interface (Flash 8)
External Interface example @ deconcept
JavaScript Integration in Flash 8

Using the XPath API in Flash

What is XPath?

XPath is a simple way by which you search through a XML document. It lets you query XML documents using names instead of the firstChild.childNodes… method.
If you are looking for a detailed explanation you can find one here : XML Path Language (XPath). This is what is mentioned in Macromedia LiveDocs about the use of XPath:

“The XPathAPI class allows you to do simple XPath searches within Macromedia Flash. This can be very useful for searching XML packets based on node names and attribute values. In other words, you can quickly find nodes and attributes in an XML document using the XpathAPI methods.”

At this point I have to mention that Flash does not support all the functionalities of XPath API as defined by the XPath standard documents. Flash provides support to only a small subset of the XPath API.

What’s the use of XPath?

XPath saves lot of time which you spend figuring out which node/s you want to target and retrieve value from. XPath existed from MX2004 days but wasn’t documented, but in Flash 8 it is documented. Flash 8’s in build help doesn’t provide much of details on using XPath but there is a link to the LiveDocs which points to a PDF file which has all the public methods listed and examples for using them.

How to use XPath in Flash?

There are two things that you have to do to get XPath working. The first is to import the XPathAPI class like this:

import mx.xpath.XPathAPI;

and next to have a instance of DataBinding classes (Window &gt Common Libraries &gt Classes) in your document. You can drag a instance of the DataBinding class into your document.

Now you are ready to start using the XPath API.

The XPath API class contains the following public methods:

XPathAPI.getEvalString()
XPathAPI.selectNodeList()
XPathAPI.selectSingleNode()
XPathAPI.setNodeValue()

In this tutorial I am going to deal with two of these API’s XPathAPI.selectNodeList() and XPathAPI.selectSingleNode()

XPathAPI.selectNodeList()

This method retrieves the nodes of a specified node path.

Syntax:

XPathAPI.selectNodeList(node, path)

Let’s start with an example XML of the site index of this site

Have a look at the actual XML here.

Now if I want to retrieve the value of all the title’s, the path would be \rss\channel\item\title and the node would be this.firstChild.
So in this case I would use the selectNodeList as:

XPathAPI.selectNodeList(this.firstChild, “/rss/channel/item/title”);

This statement would return me the array of all the titles.

Example:

import mx.xpath.XPathAPI;

var rss:XML = new XML();
rss.ignoreWhite = true;
rss.onLoad = function(success:Boolean) {
if (success) {
// Retrieve all titles in the path /rss/channel/item/title.
var titleArray:Array = XPathAPI.selectNodeList(this.firstChild, “/rss/channel/item/title”);
for (var i:Number = 0; i < titleArray.length; i++) {
trace(titleArray[i].firstChild.nodeValue);
}
} else {
trace(”XML loading failed !!!”);
}
};
rss.load(”http://www.lastashero.com/tutorials/index.xml”);

This code will trace the following values in the output window :

Automating Meta Data insertion using JSAPI
Using SWF Metadata in Flash 8
Creating a File upload application using FileReference API
Using the onHTTPStatus handler
Flash 8 - Object Drawing Model

XPathAPI.selectSingleNode()

XPathAPI.selectSingleNode method is very similar to XPathAPI.selectNodeList, except for the fact that XPathAPI.selectSingleNode retreives the value of a single node instead of multiple nodes as in XPathAPI.selectNodeList.

Syntax:

XPathAPI.selectSingleNode(node, path)

Going by the old example, if you want to retrieve the value of the first title node the code would be :

import mx.xpath.XPathAPI;

var rss:XML = new XML();
rss.ignoreWhite = true;
rss.onLoad = function(success:Boolean) {
if (success) {
// Retrieve the title of the first node in the path /rss/channel/item/title.
var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, “/rss/channel/item/title”);
trace(titleNode.toString());
} else {
trace(”XML loading failed !!!”);
}
};
rss.load(”http://www.lastashero.com/tutorials/index.xml”);

This code will trace the following values in the output window :

<title>Automating Meta Data insertion using JSAPI</title>

The following path expressions can be used for the query:

Absolute path :

/item/title

Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, “/rss/channel/item/title”);

Relative path :

title (if the context node is )

Example: Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, “title”);

Wildcard (*) :

/*/title - retrieves all <title> elements,whatever the parent node is

Example : var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, “/rss/*/title”);

Predicate expressions using =, AND, or OR :

/item/title[@version='current']
or:
/item/title[@version='current' AND
@post='today']

Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, “/item/title[@version='current' AND @post='today']“);

Documentation:

You can download the PDF from LiveDocs which contains all the methods and the usage from here.

If you have Flash 8 Pro / MX2004 Pro installed you can check out the actual class here :

C:\Documents and Settings\[User]\Local Settings\Application Data\Macromedia\Flash 8\[Language]\Configuration\Classes\mx\xpath\

Related readings:

XPath in Flash
Using XPath with Flash
XPath in Flash - there’s always more than one way to go
Using XPath in Flash

Automating Meta Data insertion using JSAPI

As I mentioned in my previous post on Using Metadata in Flash 8, you can automate the process of inserting meta data into your Flash document by using JSAPI commands.

The code below creates a new FLA and addes the Title and Description to the newly created document.

// Create a new timeline-based FLA document

fl.createDocument();

// Retreive the document object (DOM) for the active FLA

doc = fl.getDocumentDOM();

// Intialize a variable with the current date

var today = new Date();

// Intialize a variable with the Title of the document

var docTitle = “Last ActionScript Hero : SWF Metadata Tutorial”;

// Intialize a variable with the Description of the document

var docDesc = “This is a tutorial that teaches how to use SWF Metadata in Flash 8″;

// Create a RDF XML in the specified syntax using current date, title and description

var rdfXML = ‘<rdf:RDF xmlns:rdf=”http://www.w3.org/1999/02/22-rdf-syntax-ns#”><rdf:Description rdf:about=”" xmlns:dc=”http://purl.org/dc/1.1/” dc:title=”‘+ docTitle +’” dc:description=”‘ + docDesc+’” /><rdf:Description rdf:about=”" xmlns:xmp=”http://ns.adobe.com/xap/1.0/” xmp:CreateDate=”‘+ today +’” xmp:CreatorTool=”Flash Authoring WIN 8,0,0,215″ /></rdf:RDF>’;

// Add the RDF XML to the current document (Sets the meta data)
doc.setMetadata(rdfXML);

Copy & Paste the above code in a new JSFL file and save it as CreateDoc.jsfl and move this file to the commands folder : C:\Documents and Settings\<user>\Local Settings\Application Data\Macromedia\Flash 8\<language>\Configuration\Commands\

Restart Flash and choose Commands > CreateDoc

This will create a new FLA document with the specified Title and Description.

Donwload : CreateDoc.zip

Next Page »

© 2007 ActionScript 3.0