Calling a JavaScript function from Actionscript 3 (Flash)

It’s very easy:

import flash.external.ExternalInterface;
...
ExternalInterface.call("your_javascript_function()");

You can even get a return value:

var x:int = ExternalInterface.call("get_x()");

To pass an argument try:

var retval:int = ExternalInterface.call("some_js_function()", "the-argument");
Calling a JavaScript function from Actionscript 3 (Flash)
Filed under: Actionscript,Flash,JavaScript,Web Development   Posted by: CodingRecipes

56 Comments »

  1. Taha:
     

    Nice Man.. Thanks

    Comment

     
  2. Pierre:
     

    Cheers awsome man, thanks!

    Comment

     
  3. Kevin:
     

    Good to know, thanks.

    Comment

     
  4. farid:
     

    hi man ,
    i think this is wrong syntax !!!!!!!!!!
    ExternalInterface.call(“your_javascript_function()”);
    because here you passed 0 arguments to the function , and when we want to pass arguments to external interface function we are using
    ExternalInterface.call(“your_javascript_function”,”red”);
    not
    ExternalInterface.call(“your_javascript_function(red)”);

    ——————————
    so i think if you would not to pass any aruments to function you should write
    ExternalInterface.call(“your_javascript_function”);
    without ===> “()”
    ————————–
    cheers ;)

    Comment

     
  5. Codehead:
     

    Well, it’s not “wrong syntax”, () works fine, traditionally it’s associated with functions, even in JavaScript when you use setTimeOut if you include () it will work just fine…

    Comment

     
  6.  

    :) Cool, Thanks.

    Comment

     
  7.  

    Pro. Very helpful for my API for my site/flash games..!

    Comment

     
  8. Moatist:
     

    Thanks man!

    Comment

     
  9.  

    Thanks a lot for this useful article. But I had difficult time navigating past your web site because I kept getting 502 bad gateway error. Just thought to let you know.

    Comment

     
  10. Ruth Ruthy:
     

    Your great tip might lead to me getting a full night’s sleep! Thank you! I have a question, just to make sure I’m getting this right.

    If I put the following AC3 code on the very last frame of my Flash movie will it call my JS function correctly?

    import flash.external.ExternalInterface;
    ExternalInterface.call(“javascript:parent.splashpage.closeit()”);

    Thank you in advance for your assistance
    -RR

    Comment

     
  11. Codehead:
     

    Ruth, honestly I don’t know, the best way to find out is to try it I guess :)

    Comment

     
  12.  

    Whoa, that was way easier than what I’ve been trying to do
    Now…
    What if I wanted to call that Javascript from a click or mouse over from the Action Script?

    Comment

     
  13. Auzzie:
     

    Hello,
    Stumbled across this post searching for another solution and it helped me a lot.

    I was trying to apply it to a separate issue that involved a jquery script and was wondering if this solution would work for that.

    The as3 needs to pass an anchor tag string to the jquery to initiate a smooth scroll script.

    This is the script that controls the scroll:

    $(document).ready(function(){
    $.smoothAnchors(3500, “swing”, true);
    });

    Would this solution work?

    Comment

     
  14. Codehead:
     

    You can always wrap the jQuery script in a function and call that function from Actionscript…

    Comment

     
  15. Casius:
     

    Hi People!
    I have some problem: my flash get a variable (Link) from html and use it for a url, i get by example: Link=”www.site.com” and then i use

    goToURL(Link, “_blank”);
    function goToURL(URL, sType:String) {
    var request:URLRequest = new URLRequest(URL);
    try {
    navigateToURL(request, sType);
    }
    }

    that works fine for “simples” url or “.php” but i cannot execute a function in javascript like:
    Link=”ExternalInterface.call (‘alert’,'Esta info!’)”

    Any suggestion?

    Comment

     
  16. Codehead:
     

    ExternalInterface.call (’alert’,’Esta info!’) is not a URL that you can pass as a string, you must execute/call ExternalInterface.call (’alert’,’Esta info!’)

    Comment

     
  17. Casius:
     

    Well, i finally found the way to pass a variable from html to flash to execute some function in javascript, this is sLink=”javascript:alert(‘Info!’)”;

    Comment

     
  18. SeriousSamP:
     

    HI,
    I’m just learning AS3 and am working on a project that uses flash to change the contents of iFrames using JavaScript. I tried using your code to call the script but it goves the error

    1084: Syntax error: expecting identifier before tripledot.

    What am I doing wrong?

    Comment

     
  19. SeriousSamP:
     

    OK I take that back works without the tripledot. Thanks man great tut.

    Comment

     
  20. Marcone:
     

    Hi there.

    When u say:

    var x:int = ExternalInterface.call(“get_x()”);

    U mean get_x() being a function returning some value? Is it possible to recover multiple variables from a single function?

    Thanks in advance.
    Marcone

    Comment

     
  21. Codehead:
     

    Marcone, I honestly didn’t ever try this but if I wanted to do this I would start experimenting with returning an array from the JS function instead of a single value…

    Does that make sense?
    :)

    Comment

     
  22. Max:
     

    Greetings, Hamid!
    How to receive “url” a hosting from which start SWFfile (itself SWFfile to be on other host)…

    More in detail:
    - Is “host.com” on which it is stored SWF…
    - There is an unknown person second_host_name.com which starts it (SWF)
    - How to learn second_host_name? (AS3 tools)

    If it is possible more in detail!
    Thanks, yours faithfully!

    Comment

     
  23. Codehead:
     

    Max, there is an easy way to do this, you go to your hosting package’s logs > Recent Visitors (or similar) and find the SWF file, then look at the ‘HTTP Referer’ and you will see the page in which this file is used.

    (I’m not sure about this one) The other thing is you probably could check for the HTTP Referer header inside the SWF file and send it to a PHP script…

    Sorry I don’t have a lot of time to explain now but use the first method or Google the second one.

    Good Luck :)

    Comment

     
  24. Max:
     

    Thx CodeHead!
    With PHP there is no possibility to connect, eat only loaded SWF unfortunately, and all…

    It is a pity that there is no time… :( Your help would help Me!
    If there will be time, I ask you, give some minutes…

    Your logic is clear, the only thing that not absolutely it turns out to carry out it

    //
    if (flash.external.available)
    try {
    var win:* = flash.external.call (“window.location”);
    }
    //

    Does not return (URL)… Do not know why?

    Thanks, yours faithfully!

    Comment

     
  25. Codehead:
     

    The problem is that window.location is not a function and the URL is actually in window.location.href so try:

    var url:String = ExternalInterface.call('function(){return location.href}');

    Or:

    var url:String = ExternalInterface.call("window.location.href.toString");

    Again, sadly I don’t have time to try these…

    Comment

     
  26. Max:
     

    Thx, Hamid! I try!

    Comment

     
  27. Marco:
     

    Thanks for the info, very helpful. But I was getting “undefined” errors when the argument was passed to the function in JavaScript. You say that having parenthesis after the function name is okay, but it’s not if an argument is added (it’s okay if no argument is present). Removing the () cured the undefined errors I was getting.

    So instead of
    ExternalInterface.call(“some_js_function()”, “the-argument”);

    It should be
    ExternalInterface.call(“some_js_function”, “the-argument”);

    The Adobe ref set me straight:
    http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html

    Comment

     
  28. ruchira:
     

    where will be that javascript function?
    wether in seperate file?
    reply please i need dat

    Comment

     
  29. Codehead:
     

    The function should be in the same page that includes the Flash (I think), it should be in the same page or one of the included JavaScript files using:

    <script src="..." ...> </script>

    Comment

     
  30.  

    Javascript is as permisive as AS1, it would have been nice that browsers implemented ECMA Script 4, strict typing rocks! then javascript would trully replace flash. Still prefer flash

    Comment

     
  31. Jason:
     

    hi, this is a great help to my project!

    Comment

     
  32.  

    This is exactly what I need to hide my Flash movie once it finishes! Thanks!

    Comment

     
  33. shirty dogg:
     

    @Codehead and @ruchira:
    The js stuff has to be in the same page anyway. What you really mean ‘the same page’? I’m pretty sure the flash object cannot perform that action before document.onready function is fired so your js function can be on very bottom on the page, can be in the frame(s) but this is the same rule to call. If you wish a new js code can be passed trough ajax and then evaluated so you can use it with the flash even this way(needs a precognitive abilities). You can even store your js code in the flash movie, append to DOM after swf is loaded and then use it or just use the lambda functions all the time as Codehead said before. Cheers ;)

    Comment

     
  34. Sérgio:
     

    hey guys, a tip for all who use JQuery like me:
    if you define functions inside the: $(document).ready(); in your javascript file, it’s don’t work with the External of Flash.
    Define your functions in other file, without the $(document).ready(), only with the function.
    =)

    Comment

     
  35.  

    I NEED TO AD
    window.addEvent(‘domready’, function(){
    var overlay = new overlay();
    var box = new multiBox(‘mb’, {
    overlay: overlay
    });
    });

    but i get 1120: Access of undefined property window.

    Comment

     
  36.  

    thanks, will be using this to implement the like button in flash.

    Comment

     
  37.  

    Thanks a lot, saved a lot of time for my project! :)
    Works great.

    Comment

     
  38. Offi:
     

    Thanks for your recipe, Hamid!

    Please, correct one mistake in code:

    ExternalInterface.call(“some_js_function()”, “the-argument”);

    to:

    ExternalInterface.call(“some_js_function”, “the-argument”);
    —————-
    Single functions call can be with or without “()”, but if you need to send any parameters you’ll get “undefined” in javascript with this.

    Comment

     
  39. Benjamin:
     

    Regarding the use of “()” in the first argument, Hamid is correct to say that it is *not* incorrect syntax, but if you want to send arguments then do not use () after the function call. In essence this calls the function alone without sending any arguments.

    As for passing multiple arguments, you can! In fact you are not limited to the number of arguments you are allowed to send. Here’s an example:

    AS:
    ExternalInterface.call(“sayHello”,”Hamid”,”Benjamin”,”awesome site”);

    JS:

    function sayHello(nameTo,nameFrom,forWhat){
    var strng=’Hello ‘+nameTo+’. My name is ‘+nameFrom+’.';
    strng+=’ Thank you for the ‘+forWhat+’.';
    alert(strng);
    }

    In the above example I sent 3 arguments to the function called sayHello which uses the javascript alert function to give a greeting using all 3 arguments.

    Comment

     
  40. George Garchagudashvili:
     

    Hello Codehead Thanks for sharing nice tutorial.
    But unfortunately I can’t make ExternalInterface.call(“functionName”,”param(s)”); work properly, even if I call this function first it stops my other as3 script working.
    Any Ideas?

    And one more question:
    when I use function to communicate with JavaScript or navigateToURL() to link buttons in flash, when displayed in browser it ask whether let or not flash to communicate with ‘this internet-enabled’ location,
    I know how to allow or deny it with adobe flash player settings manager is it possible to use this function without depending on users settings?

    Thanks

    Comment

     
  41. Paul:
     

    Hi Codehead, You seem to have a good grasp on calling-a-javascript-function-from-actionscript and hope you may understand the issue I am having!!

    Im trying to close a netStream from a html button.
    I dont now how to pass the btn function to the ExternalInterface.call(“your_javascript_function()”);

    Heres my bad code; hope you may take a look! :) Many Thanks Paul

    //AS3
    ExternalInterface.addCallback(“sendToActionscript”, callFromJavaScript);

    function callFromJavaScript():void
    {
    nsStream.close();
    }

    //JS
    function getFlashMovie(movieName) {

    var isIE = navigator.appName.indexOf(“Microsoft”) != -1; return (isIE) ? window[movieName] : document[movieName];
    }

    function callToActionscript(HD01) {
    getFlashMovie(HD01).sendToActionscript();
    }

    //btn
    OnClientClick=”callToActionscript();”

    Comment

     
  42. Wilson:
     

    In my case, the javascript calling wont function if i added “()” in the function name. so i think the “()” is not needed. Thanks anyway.

    var x:int = ExternalInterface.call(“get_x()”);
    To pass an argument try:
    var retval:int = ExternalInterface.call(“some_js_function()”, “the-argument”);

    Comment

     
  43. Adam L:
     

    The last example of this I saw didn’t include a return statement. You made it very simple, thank you very much!

    Comment

     
  44. Adam L:
     

    I mean an import statement, not a return statement.

    Comment

     
  45.  

    Hey

    Thanks alot for this great and simple explanation, really helped me alot :)

    -Kim

    Comment

     
  46. Mohan:
     

    hi, this is a great help to my project!

    Comment

     
  47. Victor:
     

    Thanks a lot!

    Comment

     
  48. Fractalized:
     

    To pick up on an earlier comment posted by Farid…

    ‘…so i think if you would not to pass any arguments to function you should write
    ExternalInterface.call(“your_javascript_function”);
    without ===> “()”.’

    I have found that passing a js function in this manner, ie. without parentheses, is the only way to make things work if you want return values to actionscript (3.0). When things don’t work, where you can’t seem to get javascript return values, there are no errors.

    Otherwise things work with or without empty javascript argument.

    This website gave me good guidance and I appreciated it.

    Comment

     
  49. colo:
     

    Gracias!!!

    Comment

     
  50. Talha Kamran:
     

    Hi,
    Need help. kind of in a pickle.
    Someone asked me to create a RSS feed reader and it appears that swf files can not load xml data on a different domain. (Tell me if it is possible to load data cross domain)

    so i decided to use XMLHttpRequest to pull XML and then load it in Flash. What is the best way to pass that entire XML to flash movie.

    Thanks,
    Talha

    Comment

     
  51. jitender:
     

    Hi

    i have try this below code for Call a javescript function.

    import flash.external.ExternalInterface;
    ExternalInterface.call(“alertB()”);

    But When i check this on brower, Browser is displayed a error.
    Flash player eneble security . Something ok setting

    Comment

     
  52.  

    Thank you. Very helpul !

    Comment

     
  53.  

    I thought I should let you guys know that I was trying to get a js variable into Flash. I was getting NUlls and had no idea why , it was because of the syntax:

    X:String = ExternalInterface.call(“get_X”);

    don’t add the paren to get_X, so don’t do:
    ExternalInterface.call(“get_X()”);

    that will return null, you need it WITHOUT the paren. Hope that helps!

    Comment

     
  54. Hovik:
     

    hello there :)
    well i find it by googling & seams ok for all but it doesnt work for me. im new & not a Adobe developer.
    this is my scenario :
    i have a pic in my stage & code below as my code. I publish it in a HTML & add a btnClick function in it. none of 2 ways of calling works.

    stage.addEventListener(MouseEvent.CLICK, ClickFunc);
    function ClickFunc(evt:MouseEvent):void
    {
    ExternalInterface.call(“btnClick()”);
    ExternalInterface.call(“btnClick”);
    }

    any help will be appreciated

    Comment

     
  55. Hovik:
     

    hello again :)
    well Im sorry its working, but there is a TIP!
    u have to use it in IIS mode & also function without ()

    ExternalInterface.call(“btnClick”, “param”);

    tnx again

    Comment

     
  56.  

    wow Thx man. Nice Job

    Comment

     

RSS feed for comments on this post. TrackBack URL

Leave a comment