Flex Mobile: Invoking JavaScript in a StageWebView

The StageWebView allows you to render HTML content inside a Flex application using the underlying HTML rendering engine available on your mobile device.

In some situations, the Flex application may need to communicate with the HTML document hosted in the StageWebWiew. In other words, you may need to invoke a JavaScript function available in that document from the Flex application.

The basic approach is to use the StageWebView loadURL() function with the javascript: protocol as follows:


For example, if you need to invoke the addItem() function providing the firstName and lastName values captured in the Flex application, you’d do something like this:

stageWebView.loadURL("javascript:addItem('" +
        firstName.text + "', '" + lastName.text + "')");

iOS Technique

On iOS however, you can’t currently use the javascript: protocol to invoke a function using loadURL() as described above. What you can do is use the javascript: protocol to change the location of the document. So the trick is to just change the hashtag at the end of the URL as a “signal” to tell the page you want to execute an action (if the base URL doesn’t change, the page is not reloaded). You can come up with your own hashtag format convention to specify the method to invoke and parameters to pass. In this case, since I only have one method to invoke, I just use the hashtag to pass the values (first name and last name).

webView.loadURL("javascript:window.location='http://foo.com/bar.html" +
        "#" + firstName.text +
        "&" + lastName.text +
        "&" + counter + "'");

NOTE: The incremented counter is used to ensure that the hashtag is changing on consecutive method invocations even if the first name and last name are the same (otherwise the onhashtag event would not fire).

In the HTML page, we use the onhashchange event to listen for hashtag changes and then trigger the appropriate action. My JavaScript looks as follows:

function addItem(firstName, lastName) {
	var list = document.getElementById('list');
	var li = document.createElement('li');
	li.appendChild(document.createTextNode(firstName + " " + lastName));

window.onhashchange = function() {
	var newHash = window.location.hash.substring(1);
	var a = newHash.split("&");
	addItem(a[0], a[1]);

Final Note

The Flash Builder simulator does not support the onhashchange event. So to test my application in the simulator (and to use the default approach when not on iOS), I use the following code:

if (Capabilities.os.indexOf("iPhone OS") == -1)
	webView.loadURL("javascript:addItem('" +
		firstName.text + "', '" + lastName.text + "')");
	webView.loadURL("javascript:window.location='" + url +
		"#" + firstName.text +
		"&" + lastName.text +
		"&" + counter + "'");

You can download the Flex project here: http://coenraets.org/webview/StageWebViewJavaScriptDemo.fxp

The HTML and JavaScript files are here:

  • Ben Clinkinbeard

    I’ve been using the javascript:someFunction() syntax on iOS without issue.

  • Pingback: Notes to myself | Axelology()

  • Ganesh

    my flash builder 4.5 does not show option for mobile platform for ios and blackberry it just show option for android
    current i am using flash builder 4.5
    flex sdk updates to 4.5.1
    stiill its not working
    check inage on=http://forums.adobe.com/thread/883052

  • When passing parameters like that in a string, you also escape special characters.
    If someone’s name contains a quote (‘) character, this will break.

    In this example that is a relatively harmless bug. If your parameters come from an untrusted source, then you have created a cross-site-scripting vulnerability.

  • amlan

    Thanks for the great example but can you show a demo of how to do the same thing with a local javascript/html file( containing the javascript) file (in the assets folder of the project).

    Thanks in advance

    • I would like a demo of this too Christophe. Please make a demo.

  • HAve you experienced any problems when you execute 2 (or more) after each other in iOS? Cause when I’m doing this the javascript is call twice, but the parameters have the value of the parameters you passed a long with the last method call.

    So for example:
    first call:
    firstname: Maikel
    lastname: Sibbald

    second call:
    firstname: Christophe
    lastname: Coenraets

    I receive in the javascript twice Christophe Coenraets.
    It’s working for me when I setTimeout of 2 sec. But that’s not a option for me.. isn’t there some event or call back option to tell actionscript its ready for another call..



    btw. good article!

  • Pingback: WebView - Flashforum()

  • Pingback: Using JQuery in a Flex Application | iPad Lessons()

  • Apinan

    The call can be made but anybody knows how can we get the return value from javascript function?

  • Hi, you can use the stagewebviewbridge class to do this sort of communication. http://code.google.com/p/stagewebviewbridge/

    by nos the only problem is that it don’t work in android, but i am finishing the modifications to do it …

  • Mamta

    I am using stageWebView for showing webpage in my mobile app but don’t know how to move back to my app once it gets loaded. In application descriptor file, I had already registered custom uri scheme (myapp://) for IOS devices and from the loaded page inside stageWebView, I was trying to call following URL myapp://webcam. But nothing had happened. It neither called LOCATION_CHANGE event of StageWebView not called INVOKE_EVENT of nativeapplication.

    How can I fix this issue?

    Thanks in advance,

  • Thanks, this blog is very good!!

  • Hi,

    I have update the StageWebViewBridge class to work with android and some other improvements…


    StageWebViewBridge is an extended version of flash.media.StageWebView.

    Extends Bitmap class, you can modify his x,y,alpha,rotation,visible, etc ( Version 1 Beta )
    Communicates Actionscript with Javascript.
    Communicates Javascript with Actionscript.
    Load local files and resources in a easy way.
    Extends loadString method with AS3 – JS communication.
    Extends loadString method to load local resources.
    Lets you take an SnapShot to use as the bitmapData of the bitmap.

  • sunil

    I am trying to run Flex mobile app using StageWebView in android emulator. I have installed AIR3.0 and FlashPlayer 10.1 in the emulator. When i run the apk, android emulator asks for FlashPlayer to be installed. Why is it so when the Flash Player is already available? Any clues..

  • Pingback: Using jQuery in a Flex Application()

  • Raja


    Im using StageWebView to display a webpage on my Android Application…..Can any one please help me , how to change the Default WHITE Background color of the StageWebView….


  • Raja

    Hi, Can any one please help me how to change the stagewebview background colour from default white…also is it possible to get Swipe Event on StageWebview?

  • Really nice!
    What if i have to do the opposite?
    Call a function in my html page to comunicate with my application?


  • Pingback: Using jQuery in a Flex Application | TechnoVeille()

  • […] JQuery in a Flex Application This is a follow up to my previous post on how to invoke a JavaScript function in an HTML document hosted in a Flex application (using the […]

  • Good example, Thanks Coenraets.

  • Thank you for the code.

  • Hi Christophe,
    do you know if the last vesrion of the Flash Builder (4.7 Premium) support the onhashchange event ? I’m running into trouble with some javascript usage in my mobile application…

  • Siva

    Hi Christophe,

    i am able to call a js function from flex through StageWebView.loadURL(). Likewise is it possible to call or callback flex function from .js?


  • Harsh Vardhan

    Hi, thanks for the guiding us out, really helpful.
    Anyways I was enjoying calling function from flex to JavaScript and vice verse, until I have to pass whole XML as string to JavaScript. When I tried it, it just did not. I don’t know if there is any limit or if there is, how much it is.

    Have anyone of you had seen this problem? Any clue would be helpful.

  • Andrew Orwill

    Hi Christophe,

    I am developing reader application in flex 4.6. I am using StageWebview to display my content.I want change the stagewebview fontsize when the user click my customized zoom button. How can i do this..

  • Hi there! This blog post couldn’t be written much
    better! Looking at this article reminds me of my previous roommate!
    He always kept talking about this. I am going to forward
    this post tto him. Fairly certain he will have a great read.

    Thankks for sharing!

  • Marquees are great for every occasion, due to the Irish weather we are limited to certain months and times of the
    year but overall no matter what the event a
    marquee lets you celebrate in style. Parties interested in booking helicopter charter and landings for the 2012
    FORMULA 1 UNITED STATES GRAND PRIX’, should contact Charlie Bravo Charter at charter@wepushtin.
    As seen previously, the Canada Nintendo Examiner has received
    a Nintendo 3DS and three titles for it.

  • Hi there! This blog post couldn’t be written any better!
    Going through this post reminds me of my previous roommate!
    He continually kept preaching about this. I
    will send this post to him. Pretty sure he’ll have a good read.
    I appreciate you for sharing!

  • Today, I went to the beach front with my kids. I found a
    sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She
    put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is completely off
    topic but I had to tell someone!

  • Excellent website. A lot of useful information here. I’m sending it to a few friends
    ans additionally sharing in delicious. And naturally,
    thanks for your effort!

  • I am sure this post has touched all the internet people, its really really
    nice piece of writing on building up new weblog.

  • Family, Friends and Relatives – Actually these are your first potential
    customers. Have you typed into Google “how can I earn online and come”
    across a few through products that seem too good to be true.
    Set up your blog or website and start writing articles
    to submit.

  • People go out with items like car keys, house
    keys, wallet and mobile phones. By learning to successfully and efficiently market your network
    marketing business online, you can connect with these motivated
    entrepreneurs. With this system in store shelves everywhere, handheld fans are
    greeted with joy and also receive many loves for Nintendo.

  • What i don’t realize is inn trfuth how you are now not really much more well-favored than you may be now.
    Yoou are very intelligent. You realize thujs significantly in relation to this subject, produced me for my part imagine it from numerous varied angles.
    Its like men and women don’t seem to be interested except it’s something to do with Woman gaga!
    Your personal stuffs great. At all times take care of it up!

  • Hello Dear, are you truly visiting this website on a regular basis,
    if so after that you will absolutely take fastidious

  • You don’t want to dampen the mood (pun intended) having to wear wet clothing.
    Both are means of transportation that can take to any destination you want.
    That is why you get anywhere from 60 to 85 percent or more of
    your stopping power from your front brake.

  • Greetings from California! I’m bored to death at work so I decided to check
    out your blog on my iphone during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I get home.

    I’m shocked at how fast your blog loaded on my mobile .. I’m not even using WIFI,
    just 3G .. Anyways, wonderful site!

  • This page really has all the info I wanted concerning this
    subject and didn’t know who to ask.

  • great submit, very informative. I’m wondering why
    the opposite specialists of this sector do not realize this.
    You should proceed your writing. I am confident, you have a huge readers’ base already!

  • Eliad

    Thank you!!

  • Right now it appears like Drupal is the top blogging platform available right now.

  • Mano


    I am using stagewebview to call a javascript function in flex mobile application.
    I am passing a selected item value to a javascript function like below:

    webView.loadURL(“javascript:myfunction(‘” + lst.selectedItem[‘name’] + “‘)”);

    and in my html file in js when i add an alert i am getting the value too.

    But the problem is the required function is working only when i add this function in onload in body as below:

    but when i remove the onload method from the body of html and call it from flex the required action is not happening inside the JS function.

    Please help me out on what is causing the issue??.

  •   His highest production of our company, we use the sport socks products: cotton, cotton, polyester, nylon and lycra. Anti-bacterial means comprises

  • yuvaraj singh

    Informative content , Great work
    Leanpitch provides online training in Product Management Launchpad during this lockdown period everyone can use it wisely.
    Product Management Launchpad