简体   繁体   中英

Use Javascript to call method within a flash (.swf) file?

I have a flash file that contains a package "game" which has a class "Scores" and a method setValue(). I want to write some lines of Javascript that allow me to call that method. Someone directed me to this tutorial, but I am still a bit confused.

Javascript: alert("start"); var so; so = document.embeds[0]; 
so.addParam("allowScriptAccess","always");  import flash.external.ExternalInterface; 
ExternalInterface.call("setValue[2600]");
  1. displays an alert to tell me that it has indeed began to execute
  2. saves the embedded flash file into a variable and sets access
  3. imports that class
  4. calls the method

I am not sure about how this class thing works? This is just the bits and pieces I was able to come up with from that site, but I don't really understand how it all works (but certainly hope to eventually). This is the site: http://bytes.com/topic/flash/answers/694359-how-do-i-access-flash-function-using-javascript . When I execute the code with the importation nothing happens, but the alert does come up when I don't have that statement?

If someone could elaborate on how I might call that method, I would be very thankful! :)

The code you have there is a mix of JavaScript and ActionScript.

In ActionScript, you need to register the setValue function for external use, so it can be called from JavaScript. Code for it could look something like this:

package game
{
    import flash.display.Sprite;
    import flash.external.ExternalInterface;
    import flash.text.TextField;

    public class Scores extends Sprite
    {
        public var txtScore:TextField;      // A textfield in the sprite

        public function Scores()
        {
            // Register the function for external use.
            ExternalInterface.addCallback("setValue", setValue);
        }

        private function setValue(value:Number):void
        {
            txtScore.text = String(value);
        }

    }

}

And the JavaScript could look something like this:

var so = document.embeds[0];
so.setValue(2600);

Adobe has the documentation with a lengthy but useful example here . They show the ActionScript as well as the JavaScript, and how they can interact in both ways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM