Send array from Flash (AS3) to JavaScript
Asked Answered
P

3

8

Is it possible to send an array from Flash (AS3) to JavaScript using an ExternalInterface call?

I currently am calling a function multiple times from a 'for each' loop inside Flash but it goes too fast for the JavaScript to keep up.

My idea is to create an array of the attributes, pass that to the JavaScript function and then to loop through that in the JavaScript.

Thanks, Josh

Picturize answered 29/6, 2009 at 14:20 Comment(1)
Just found this which maybe causing my issues scottgmorgan.com/blog/index.php/tag/externalinterface Still interested in the array though if possible.Picturize
G
7

Further to the suggestion of using JSON, this should be faster for small arrays and wouldn't require the use of eval or an external library to parse. Join an array in a string like this in flash:

item1|item2|item3|item4

Pass the string to the JS and split it again using split("|")

Greenes answered 29/6, 2009 at 14:42 Comment(1)
Just be sure your data will never contain the separator character(s)!Phile
P
8

Yes, it's possible.

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html#call()

... arguments — The arguments to pass to the function in the container. You can specify zero or more parameters, separating them with commas. They can be of any ActionScript data type. When the call is to a JavaScript function, the ActionScript types are automatically converted into JavaScript types; when the call is to some other ActiveX container, the parameters are encoded in the request message.

A quick test:

AS code:

if(ExternalInterface.available) {
    ExternalInterface.call("jsTest", [0,1,"two",{a:1,b:2}]);
}

JS code:

function jsTest(arg) {
    alert(arg);
}
Policeman answered 30/6, 2009 at 1:42 Comment(0)
G
7

Further to the suggestion of using JSON, this should be faster for small arrays and wouldn't require the use of eval or an external library to parse. Join an array in a string like this in flash:

item1|item2|item3|item4

Pass the string to the JS and split it again using split("|")

Greenes answered 29/6, 2009 at 14:42 Comment(1)
Just be sure your data will never contain the separator character(s)!Phile
L
6

You could always create a JSON object and pass that to JavaScript.

Lineage answered 29/6, 2009 at 14:23 Comment(2)
JSON is fine and there are plenty of libraries you can use both on Actionscript and Javascript. In this case, though, the player handles the serialization for you, so I would just use native AS objects. It's simpler, already available off the shelf and probably faster.Policeman
while receiving a json object how do you store it in flash in a string?Elsaelsbeth

© 2022 - 2024 — McMap. All rights reserved.