dopplesoldner
dopplesoldner

Reputation: 9499

javascript - unable to call function from embedded SWF

I created an AS3 script with a function

public function sayHello():String
{
    return "Hello";
}

I have also registered the callback as follows

ExternalInterface.addCallback("sayHello", sayHello);

In my javascript, I have embedded the SWF file as follows

<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
  swfobject.embedSWF("HelloWorld.swf", "HelloWorld", "1", "1", "9.0.0");
</script>

But when I try to call the sayHello method as follows

document.getElementById("HelloWorld").sayHello();

I am getting Uncaught TypeError: Cannot call method 'sayHello' of undefined

Any help will be appreciated!

Upvotes: 1

Views: 775

Answers (1)

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

If the swf isn't loaded yet then document.getElementById("HelloWorld") will return undefined hence your error. You can try if this is the case by calling that couple seconds later.

setTimeout(function() {
    document.getElementById("HelloWorld").sayHello();
},5000);

I would also put that code inside a function that is called on body onload event ie.

...
<head>
<script>

function onload() {
    setTimeout(function() {
        document.getElementById("HelloWorld").sayHello();
    },5000);
}

</script>
...
</head>

<body onload="onload()">
...
</body>

Upvotes: 1

Related Questions