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: ''

1 comment:

  1. I've just discovered this in AS2. My return value is a structured object but every element that holds an empty string, comes back as the 4-character string 'null'. This must be a bug surely! Having to parse my returned object converting 'null' (string) back to '' (string) is going to be a pain.

    It would be nice to know why the interface's data is marshalled this way.

    ReplyDelete

Was this post helpful? Do you have questions about it? Do you want to share your own programming blog? I'd love to read your feedback.

Note: Only a member of this blog may post a comment.