ExternalInterface.addCallback for as3 doesn't

2019-05-29 07:45发布

问题:

I want to call AS function from JS.

I have the following ActionScript 3 code:

package  {
    import flash.display.*;
    import flash.events.*;
    import flash.system.*;
    import flash.external.ExternalInterface;
    public class Main extends Sprite {
        public function Main() 
        {
            ExternalInterface.addCallback("PlaySound", PlaySound);
        }
        public function PlaySound():void
        {

        }
    }
}

I need to call function PlaySound() from JavaScript. I try to do it in the following way:

function thisMovie(movieName) {
   if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
   } else {
        return document[movieName];
   }
}

function m()
{
  var obj=thisMovie("Main");
  obj.PlaySound();
}

But obj has no method PlaySound() (obj is not null).

What's wrong?

回答1:

I use this to find the movie. It seems to be more reliable:

function thisMovie(movieName) {
    var movie;
    try
    {
        movie = document[movieName];
        movie = (movie == null) ? window[movieName] : movie;        
    }
    catch (e)
    {
        return null;
    }
    return movie;
}

I've also found that ExternalInterface does not work properly when running from a local filesystem. Have you tried running this from a webserver?

It's also possible that you are seeing a race condition... perhaps you are trying to call PlaySound before it has been registered as a callback. What happens if you wait a little bit before making the call?



回答2:

I think the problem is that the SWF file isn't loaded yet when you try to call it from JS.