Calling a Flex function from javascript

Update: I have updated the content of this entry after it was posted. John Dowdell(JD) pointed out some part of post which were confusing. I hope, it is clear now.

This is quite common question in Flash and Flex world. I had created JSFCommunicator library long back to facilitate JavaScript-Flash-JavaScript communication. But JSFC is supported in applications created via Macromedia Flash authoring tool, it is not straight forward to use it in Macromedia Flex applications. JSFC also has some issues in Firefox browser on MacOS. I am going to update it so that it works well on most of the browsers, operating systems and also in Macromedia Flex applications.

In flexcoders list, someone asked how to call a function in Flex app from Javascript, I wrote a simple example to show the technique. Following example is not a very OO approach, but it can easily be made more reusable by wrapping things into classes or creating a component.

JavaScript Code:

//this function return to Flash ActiveX Object or Plugin depending upon browser
//it takes care for browser type and returns the proper reference.
//Accepts the id or name of <OBJECT> or <EMBED> tag respectively
//source taken from:

function thisMovie(movieName) {
// IE and Netscape refer to the movie object differently.
        // This function returns the appropriate syntax depending on the browser.

if (navigator.appName.indexOf ("Microsoft") !=-1) {
return window[movieName];
} else {
return window.document[movieName];
//success flag, set by flash/flex app
var bFunctionCallFinished = true;
//param delimiter, kind of unique string
var paramDelimiter =  "-->$$###$$##$$<--";
//this function would call a flash/flex function.
function callFlashFunction(functionName, paramsArray)
//Get the reference so activeX or Plugin. flexApp is id/name of OBJECT/EMBED tags
                var flashObject  = thisMovie("flexApp");
bFunctionCallFinished = false;
flashObject.SetVariable("functionName", functionName);
flashObject.SetVariable("functionParams", paramsArray.join(paramDelimiter));
flashObject.SetVariable("commitFunctionCall", true);
//if previous function call is still being run, you can use setTimeOut etc to call it little later...

Flex Code(main.mxml):

<mx:Application xmlns:mx="" width="600" height="600" backgroundColor="#FFFFFF" >
//the name of the function to be called.
var functionName:String;
//the params delimited by paramDelimiter
var functionParams:String;
//param delemiter, kind of unique string
var paramDelimiter =  "-->$$###$$##$$<--";
//setter, which executes the function and send the success flag back to javascript
public function set commitFunctionCall(flag:Boolean):Void
var func:Function = this[functionName];
func.apply(this, functionParams.split(paramDelimiter));
function sayHi(name:String)
alert("Hi " + name);
_ta.text += name + newline;
function setNum()
var n = arguments.length;
for(var i=0;i<n;i++)
_ta.text += arguments[i] + newline;
<mx:TextArea id="_ta" width="200" height="200"/>

HTML Code:

<script language="Javascript" >
//above JavaScript code goes here
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase=',0,14,0' width='600' height='600'
<param name='flashvars' value=''>
<param name='src' value='main.mxml.swf'>
<embed pluginspage='' width='600' height='600'
<input type="button value="Say Hi" onclick="callFlashFunction('sayHi', ['Abdul']);" />
<input type="button value="Set number" onclick="callFlashFunction('setNum', [1,2,3]);" />

Download the complete file from:

Hope it’s useful for someone. Stay tuned, for new version JSFC library.
See complete post in flexcoder’s archive:
http:[email protected]/msg06106.html

  • Hi, Abdul. I’d like to make sure I understand this correctly:
    “But JSFC only works in Flash and has some issues on MacOS. Also it’s not yet ported to Flex.”
    Are you talking about things like LiveConnect and ActiveX Scripting here? the whole original sense of FSCommand?
    (Or is it some other approach, like “javascript:” pseudo-URLs, or JavaScript document.writes of data to FLASHVARS, or continuing server communication in browsers which support it?)
    And does “ported to Flex” mean “encapsulated in native Flex components”? That “only works in Flash” line really means “only works in the Macromedia Flash Player”, and not “only works in the Macromedia Flash MX authoring tools”, right? or am I not understanding this correctly…?

  • Hi JD,
    Sorry for delay in replying to your comment. Your comment was lost in thousands of spam comments. Also sorry for the confusion in my post..
    Following is my response to your doubts in a order:
    1) “Are you talking about things like LiveConnect and ActiveX Scripting here? the whole original sense of FSCommand?”
    John, on MacOS, SetVariable(..) or GetVariable(..) methods of Macromedia Flash Player plug-in doesn’t work in Firefox. I guess, it’s LiveConnect issue or Firefox doesn’t support this. I checked in other browsers in MacOS and I remember it worked.
    So I am about to update JSFC to use a proxy swf which passes data to main swf via LocalConnection. This proxy swf would be embedded in html dynamically using javascript’s document.write and data would be passed to it via flashvars.
    2. “And does “ported to Flex” mean “encapsulated in native Flex components”? That “only works in Flash” line really means “only works in the Macromedia Flash Player”, and not “only works in the Macromedia Flash MX authoring tools”, right? or am I not understanding this correctly…?”
    JSFC consists of a Macromedia Flash V1 component and a javascript class. So by “ported to Flex”, I mean to write a Flex component or a Flex class that works seamlessly with other components in a Flex application. In current state JSFC, it is not usable(easily) with Flex but one can use it in Flex by loading a swf containing JSFC flash component. But it’s not straight forward.
    By “only works in Flash” line really means “, I mean to say JSFC supports applications made via Flash Authoring tool. It’s not straight forward to use it in Macromedia Flex applications.
    I would like to say that, JSFC works in Flash Player, because runtime for Flash applications or Flex applications is same i.e. Macromedia Flash Player.

  • Asgar Ali

    Hi Abdul,
    I am a newbie to Flex/Flash. I’m trying to create a window and refer that window via a flash object. For eg., AppOne is my primary application from which I want to call another app, AppTwo.
    If I use the PopupManager.createPopup, the popup opens in the same browser window as AppOne. Is there any alternate way to open AppTwo in a new browser window and still refer it within your Flex App code ?
    Thanks & Regards,

  • lakshmi

    i need to cal a function where the function name is stored in variable. How to call this?
    below is the code snippet:
    function xxx()
    var scrval=”isvalidnumber()”;
    var fun = scrval+”()”;
    eval(fun); // here i need to call this function


  • Vali

    Do you know why when calling a JavaScript function
    from inside the Flash using the getURL(),
    the animated gifs stop looping ?
    for example:
    on (rollOver)
    getURL(“javascript: alert(‘after this the gifs will stop animate…’);”);

  • Maria Brown

    Great example and great code! Thanks for sharing this with others :}

  • NIks

    I have seperate html and java script file.
    now i have created a little application using flex(Active Script).
    Now i need to call that application from java script file. and Flex application takes input from same java script file and display the output in same html page.
    how can i implemrnt this scenario?
    thanks in advance

    • pinarocal

      nlks, actually we have the same problem. have you found any solution to this? if yes, can you please explain to me?
      thanx in advance

  • sneha

    Im working on a project which is required to run on cross browsers.I have to make use of same shortcut keys as there are in IE(Eg:-Ctrl+n for new window).Im trying to resolve this using javascript function& calling it from my flex application.My javascript function is working fine if im running it in HTML tags. When i call the same function from flex it runs properly for the first time but the Issue is when contrlo goes to flex function & then I press any key on my text area it do not handle it. Following is my code. Please suggest some modifications to resolve it.
    Javascript code:-
    document.onkeypress = function() {IEOnKeyPress()}
    document.onkeydown = function() {IEOnKeyDown()}
    document.onkeyup = function() {IEOnKeyUp()}
    function IEOnKeyPress()
    //alert(“In on key Press!!!”);
    var theEvent = window.event;
    var keyCode = theEvent.keyCode;
    alert(“IEOnKeyPress” +keyCode);
    if (keyCode > 31 || keyCode == 13)
    //buzzword.onKeyPressIE(keyCode, theEvent.ctrlKey && !theEvent.altKey, theEvent.altKey && !theEvent.ctrlKey, theEvent.shiftKey);
    function IEOnKeyDown()
    var theEvent = window.event;
    var keyCode = theEvent.keyCode;
    if (theEvent.ctrlKey || theEvent.altKey || (keyCode = 65 && keyCode = 37 && keyCode
    function callApp() {
    window.document.title = document.getElementById(“newTitle”).value;
    //—————————————————End Check————————————
    //————–Here goes getFlexApp——————————————————————-
    function getFlexApp(appName)
    if (navigator.appName.indexOf (“Microsoft”) !=-1)
    return window[appName];
    //alert(“Document “+document[appName]);
    return document[appName];
    Flex code:-

  • sajjad mahmood


  • atul

    i have tried you example but it doesn’t work can you some more example which are in working

  • HI,
    I know its late,
    But i wish to know that can we include .js(JAVASCRIPT) file in to mxml flex file like including javascrpit file in html.
    if s, how?
    what is the code 4 tat.
    mail me…..

  • Mysok

    unfortunately the code doesn’t work with Flex Builder 3, do you (anybody) have some update? Thank you a lot.

  • Bhavika

    i have 1 html page, from there i am calling a flex function to load swf object!
    m able to implement this successful in IE and safari,
    but mozilla says myflexfunction is not a function!

    function callApp(formid) {
    var objectChart = document.getElementById(“statisticsChart”);
    objectChart.myFlexFunction(formid, $get(”).value);}

    myFlexFunction is a flex function, statisticchart is a swf object.
    any help will be appriciated!

    • @Bhavika: I had the same problem.
      In my case it turned out, that the flex-function was invoked before the swf-object was fully loaded.
      I described the problem and my solution in more detail on my blog:

      Hope it helps…

  • pinarocal


    I have a problem. in my project i have two parts one is related with Javascript files for mozilla add on , the other is flex files which is used for graph visualization.
    the problem is that i can not manage to ensure interaction btw flex and javascript files. i want flex files take information from javascript file. that is, I want Javascript sent data to flex files.

    Can anyone help us ?

    thanx in advance

    • @pinarocal: The article on
      should give you some hints.
      I would declare a variable and a set-function in the flex file. Then call the set-function from the javascript file with the data you want to pass on to flex.
      The code in the article above works fine, so you only need to add some additional variables and functions to it.

      If that doesn’t work for you, maybe you could post a detailed description of the exact problem?

    • pinarocal

      actually i have managed interaction between flex and javascript. swf file works correctly. Now, there is a project about creating mozilla add-on. when swf file is embeded to this project, it does nothing ! i see swf is loaded but any changes that i make is not displayed correctly. i couldnt understand why it is not working when i combine it to add-on project while it works. i checked the paths, includes and everything !