ExternalInterface Bug with new line chars

A couple of days ago I ran into a bug with ExternalInterface which caused me quite a hassle (a couple of people ran into it before I did). I finally figured it out, and wanted to post here in case anyone else runs into it.


Basically, if the data being passed from JavaScript to ActionScript or ActionScript to JavaScript via ExternalInterface contains any line returns (\n) then the string is not serialized correctly, and the call will fail (you will probably see a JavaScript error). This affects both Flash Player 8, and the Flash Player 8.5 alpha.The issue has been logged and is being looked at it. Luckily, there is a simple workaround, which is to manually escape the line returns by replace \n with \\n.Here is how to do it in ActionScript 3:

var data:String = stringToPass.replace(/\n/g, "\\n" );

and here is how to do it in ActionScript 2:

function escapeLineReturns(s:String):String{trace("a");var len:Number = s.length;var sb = "";var c;for(var i:Number = 0; i < len; i++){c = s.charAt(i);if(c == "\n"){sb += "\\n";}else{sb += c;}}trace("r : " + sb);return sb;}var data:String = escapeLineReturns(stringToPass);

On the JavaScript side you can basically use the same solution as in ActionScript 3.0:

var data = stringToPass.replace(/\n/g, "\\n" );

5 Responses to ExternalInterface Bug with new line chars

  1. Brad Neuberg says:

    By the way, when you fix this bug, can you create a unit test on your side that throws alot of other crazy characters through ExternalInterface (including \r, pointy brackets, etc.)? If you are using XML as your internal serialization format, which I suspect, you might incorrectly serialize/deserialize those as well.

  2. Wes Carr says:

    There are some other characters that either cause and ExternalInterface call to fail or are not serialized properly. Here are the ones I’m aware of and their workarounds:\r >> \\r&amp; >> &amp;amp;&apos; >> &amp;apos;&lt; >> &amp;lt;&gt; >> &amp;gt;&quot; >> &amp;quot;Cheers

  3. mike chambers says:

    Thanks. I just added these to the bug.mike chambersmesh@adobe.com

  4. Kelvin Luck says:

    Could you simplify your AS2 replacement function to this:[code]function escapeLineReturns(s:String):String{return s.split(“\n”).join(“\\n”);}[/code]? Not sure if it is less efficient but it seems to work for me…

  5. Brad Neuberg says:

    It sounds like you used XML for your serialization format, but didn’t surround the value sections with CDATA blocks:That should help some of these problems, including having XML characters and entities misinterpreted. That is, if you didn’t roll your own XML parser on the other side, which doesn’t correctly handle CDATA sections, or are parsing out the XML with regular expressions….