4

Given that there is a global javascript variable on my web page named myVar, how can I access the value of the variable myVar from within my flash movie using javascript?

I see plenty of examples of using external interface in order to execute javascript from actionscript, but I am unable to find examples of returning values back into the flash movie using actionscript.

Thanks in advance. I hope my question is clear enough.

Rafe
  • 8,467
  • 8
  • 47
  • 67

4 Answers4

6

ExternalInterface works by allowing JavaScript to invoke an ActionScript function in the movie, and vice-versa. You can optionally receive a return value back from the invoked function. Here's a very simple example:

JavaScript:

<script language="JavaScript">
    function getMyVar()
    {
        return myVar;
    }
</script>

Flash/AS:

import flash.external.ExternalInterface;
var result:string = ExternalInterface.call("getMyVar");
Rex M
  • 142,167
  • 33
  • 283
  • 313
  • Nice, that's what I am trying to do right now, except I am passing the name of the variable to the getMyVar function and then returning this[myVarName]... I think this method is going to work. Thanks! – Rafe Mar 29 '09 at 02:11
  • This did in fact solve my problem. Here's what I used in javascript: function returnVar(varName) { return this[varName]; } and in ActionScript 3: var jsVariableValue = ExternalInterface.call("returnVar","jsVariableName"); – Rafe Mar 29 '09 at 02:18
  • Sounds like this could also work with AJAX and JSON for getting data to flash? – jerebear Mar 29 '09 at 05:54
  • @jerebear, except that AS has functions for even broader data retrieval. – Tracker1 Mar 30 '09 at 06:18
2

You can also provide an anonymous function that returns your global variable value to the ExternalInterface.call method as follow:

ExternalInterface.call("function(){ return myGlobalVariable; }");
1

I've noticed Rex M's answer is a bit incomplete.

He was right about using...

import flash.external.ExternalInterface;
var result:string = ExternalInterface.call("getMyVar");

Then in your javascript you can use

<script language="JavaScript">
    function getMyVar() {
        return myVar;
    }
</script>

However in order to use this, the flash movie must be in an html accessed over http. Not using file://

Here is a tutorial for communicating from actionscript to javascript and vice versa. http://www.youtube.com/watch?v=_1a6CPPG-Og&feature=plcp

dhoodlum
  • 1,103
  • 2
  • 9
  • 18
0

You can also do this:

ExternalInterface.call("eval","getVar=function(obj){return obj}");
var yourVar:String = ExternalInterface.call("eval","getVar(JSvar)");
Miki Berkovich
  • 467
  • 5
  • 16