Main

October 26, 2005

Understanding ExternalInterface in Flash 8

Listen to this article Listen to this article :: Talkr

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

October 21, 2005

Using the XPath API in Flash

Listen to this article Listen to this article :: Talkr

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 > Common Libraries > 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


October 18, 2005

Automating Meta Data insertion using JSAPI

Listen to this article Listen to this article :: Talkr

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

October 17, 2005

Using SWF Metadata in Flash 8

Listen to this article Listen to this article :: Talkr

What is SWF Metadata?

Simply put SWF Metadata is something similar to HTML meta tags. SWF Metadata is a new feature in Flash 8 that helps search engines like Google index Flash contents. This was something which was not directly possible in Flash and people used to rely on workarounds to achieve this. SWF Metadata is specified in RDF (Resource Description Framework) which is stored in the SWF which search engines can use to find relevant keywords.

How to use SWF Metadata?

The metadata for a Flash document can be specified in the document properties (Modify > Document... [Ctrl+J]). You will find two text areas titled "Title" and "Description". These are the two values which are used as the SWF Metadata for the document.

After you have specified these two values and compile your movie, the metadata values are added to the header of the SWF file which the search engine can use to index your content.

Other ways of specifying SWF metadata

If you are webmaster and want to include a standard set of keywords/title/description for all your Flash content, the JSAPI DOM provides methods by which you can insert such title and description into your document. You can set metadata using the JSAPI function document.setMetadata(). The setMetadata function takes a XML as the parameter and sets the metadata of the document. The XML that is passed to the setMetadata function can be in three formats. The various formats are described here.

The simplest form of which is :

<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='Last ActionScript Hero : SWF Metadata Tutorial' dc:description='This is a tutorial that teaches how to use SWF Metadata in Flash 8' />
<rdf:Description rdf:about='' xmlns:xmp='http://ns.adobe.com/xap/1.0/' xmp:CreateDate='2004-10-12T10:29-07:00' xmp:CreatorTool='Flash Authoring WIN 8,0,0,215' />
</rdf:RDF>

Is SWF Metadata used by all popular search engines to index contents?

The answer is NO. Not all popular search engines are build to index pages that have SWF metadata. Google for sure does this though. Do you really bother about others ;)

How do I make sure the metadata I specified for my document is embeded into the SWF?

Simple, if you look at the size report generated by Flash for your movie, you will see a row titled "Metadata" which will look like this :

meta.swf Movie Report
----------------------
Metadata
--------
Bytes Value
----- -----
227 <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>Last ActionScript Hero : SWF Metadata Tutorial</dc:title><dc:description>This is a tutorial that teaches how to use SWF Metadata in Flash 8</dc:description></rdf:Description></rdf:RDF>

To generate size report for you movie goto File > Publish Settings... > Flash > Options and check the "Generate Size Report" checkbox.

How do I search Google for SWF's that has SWF metadata embeded in them?

You can do a search by filetype and keywords in Google. For example a search for filetype:swf +"tutorial" in Google would return those SWF's which are associated with the keyword tutorial in them.

If you are looking for a specific SWF in a specific site you can use the site: and filetype: keywords in Google to specify the exact filename you are looking for in a site.

Example :

filetype:swf site:lastashero.com

October 08, 2005

Creating a File upload application using FileReference API

Listen to this article Listen to this article :: Talkr

Feature - FileReference API
Level - Intermediate
Audience - Developers

FileReference API provides methods using which one can download or upload files from/to a server. Each FileReference object maps to a single file which can be uploaded or downloaded from/to a server. You can get the following properties of a file using the FileReference API:

  • File Size
  • File Type
  • File Name
  • Creation Date
  • Modification Date
  • Creator type (Mac only)

Due to security reasons you CANNOT get the file path of the file which you are uploading to the server.

The following methods are available in the FileReference API:

and the events are:

onCancel = function(fileRef:FileReference) {}

Invoked when the user dismisses the file-browsing dialog box.

Ex: 

listener.onCancel = function(file:FileReference):Void {

    log.addItem(“File upload/download cancelled by user”);

}

onComplete = function(fileRef:FileReference) {}

Invoked when the upload or download operation has successfully completed.

Ex:

listener.onComplete = function(file:FileReference):Void {

    log.addItem(“File upload/download successful”);

    // Write code here to do manipulations or display the uploaded file

}

onHTTPError = function(fileRef:FileReference, httpError:Number) {}

Invoked when an upload fails because of an HTTP error.

Note: This event applies only to File Upload and not File Download. If a file download fails, an IO Error is reported instead of a HTTP Error.

Ex:

listener.onHTTPError = function(file:FileReference, httpError:Number):Void {

    log.addItem(“HTTP Error :” + httpError);

    // Write code here to do corrective actions

}

onIOError = function(fileRef:FileReference) {}
Invoked when an input/output error occurs.

onOpen = function(fileRef:FileReference) {}
Invoked when an upload or download operation starts.

onProgress = function(fileRef:FileReference, bytesLoaded:Number, bytesTotal:Number) {}Invoked periodically during the file upload or download operation.

Ex:

listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {

log.addItem("bytesLoaded: " + bytesLoaded + " bytesTotal: " + bytesTotal);

}

onSecurityError = function(fileRef:FileReference, errorString:String) {}
Invoked when an upload or download fails because of a security error.

Note: In most of the cases this error occurs due to the sandbox restriction. Check if the crossdomain.xml file is present and configured properly in the site to which you are uploading the file.

Ex:

listener.onSecurityError = function(file:FileReference, errorString:String):Void {

   log.addItem("Security Error: " + file.name + " errorString: " + errorString);

}

onSelect = function(fileRef:FileReference) {}
Invoked when the user selects a file to upload or download from the file-browsing dialog box.

Ok, enough of lecture. Let’s get into implementing a example using FileReference API which will be a application through which you can upload files into a web server.

So what do you need to implement this example?

  • The Flash application
  • A PHP/ASP/JSP page which will catch the file stream and create the file on the server
  • A folder on the Web server with write permission.

Flash application:

This file contains all the methods that are present in the FileReference and the usage example.

PHP code:

<?PHP
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['Filedata']['name']);

if(move_uploaded_file($_FILES['Filedata']['tmp_name'], $target_path))
{
     echo "The file ". basename( $_FILES['Filedata']['name']). " has been uploaded";
}
else
{
     echo "There was an error uploading the file, please try again!";
}
?>

For a detailed explanation of this code, see here.

Download the example files here.

Just unzip the archive into a folder and upload it to your web server and you are ready to upload files into the server.

Additional References :

Flash 8 File-Upload (RC-1)
Uploading files with Flash 8
Flash: Force Download… No more dirty tricks in Flash 8

October 02, 2005

Using the onHTTPStatus handler

Listen to this article Listen to this article :: Talkr

Feature   -   httpStatus
Level       -   Intermediate
Audience -   Developers

What is HTTP status?

In general a HTTP status is received by the browser from the server when a URL is requested. In case of Flash, the Flash player recieves a HTTP status from the server when a call is made. HTTP status messages need not be always errors. W3C clasifies HTTP status into 5 different categories based on the types of status. You can find the different types of status here.

Use of HTTP status

There are many uses of HTTP status but the primary use is to debug the application. Based on the HTTP status that is received by your application you can write code to handle a case. This is particulary crusial when creating RIA's using Flash. For instance if you are writing a application which aggregates data from different RSS feeds and if some of the servers are down then your application may not work as intended and you would spend a lot of time debugging your application, whereas the actual problem is in the server side and not with your applications. In these kind of situations HTTP status methods comes handy and can save you a lot of development time.

Flash &HTTP status

httpStaus is a new method in Flash 8 which provides a way to get the HTTP status code when trying to load data into Flash. httpStatus can be used mainly with XML and LoadVars.

LoadVars.onHTTPStatus
XML.onHTTPStatus

In the past there was no method in Flash by which you can do this except for the Log class which is used with WebServices.

Usage:

The onHTTPStatus handler is called before the onData call. The onData handler will pass undefined to onLoad handler if the loading fails .

Example:

#include "httpCodes.as"

var myXml:XML = new XML();

myXml.onHTTPStatus = function(httpStatus:Number) {
for (var i=0; i<codeArray.length; i++)
{
var errString:String;
errString = httpStatus.toString();
if (codeArray[i].indexOf(errString)>-1)
{
trace(codeArray[i])
}
}
}

myXml.load("http://www.lastashero.com/blog/index.xml");



The file httpCodes.as contains the various HTTP status codes and a very brief status message. You can download the file httpCodes.as here.

Just copy and paste the above code in your main timeline and compile the movie. The output window will display the message "200 - OK", which implies that the request has succeeded.

Now for a negative case :

Copy & paste the same code above but modify the last line from : myXml.load("http://www.lastashero.com/blog/index.xml"); to myXml.load("http://www.lastashero.com/blog/index1.xml");
Now when you compile the movie, since index1.xml does not exists on the server your output window will display the message "404 - Not Found". Which is the famous Page Not Found error.

If you want to take decisions based on the type of HTTP status, you can use the code which comes with the examples in Flash 8. So if the status is Information or Success messages you can trivially ignore them and if they are error messages, you can take corrective measures based on the error code.

Additional Resources :

LoadVars.onHTTPStatus
XML.onHTTPStatus

Sample:

This SWF queries various feeds listed in MXNA and returns the status. This is a quick example which I constructed and the code is not optimized, once I come up with a proper example I will post the file here.