how to read a global javascript variable from actionscript

这一生的挚爱 提交于 2019-12-05 16:10:23

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");

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; }");

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

You can also do this:

ExternalInterface.call("eval","getVar=function(obj){return obj}");
var yourVar:String = ExternalInterface.call("eval","getVar(JSvar)");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!