Wednesday, February 4, 2009

ExternalInterface vs. JS function returning empty-string

The Problem

I have a JavaScript function that always returns a string, but in some cases it needs to return an empty-string. I have Flash, using ActionScript 2, call this function using ExternalInterface.call, but surprisingly when the return value of the JavaScript function is empty-string, ExternalInterface.call returns the 4-character string: "null". If using ActionScript 3, the value null is returned instead of the string.

Example
JavaScript:
function test(bln)
{
   return (bln ? "some text" : "");
}

ActionScript:
import flash.external.*;

ExternalInterface.call(
    "alert",
    "'" + ExternalInterface.call("test", true) + "'");
    //alerts: 'some text'

ExternalInterface.call(
    "alert",
    "'" + ExternalInterface.call("test", false) + "'");
    //alerts: 'null'


The Solution

The workaround is to detect "null" or null and replace it with empty-string, as in these examples:

ActionScript 2 workaround
import flash.external.*;

var x = ExternalInterface.call("test", false);

if (x == "null")
    x = "";


ExternalInterface.call("alert", "'" + x + "'"); //alerts: ''

ActionScript 3 workaround
import flash.external.*;

var x = ExternalInterface.call("test", false);

if (x == null)
    x = "";


ExternalInterface.call("alert", "'" + x + "'"); //alerts: ''