UPDATE: there’s a newer post about this same thing (actionscript javascript communication – but in as3)! I encourage you to check it out!
Overview:
Using ExternalInterface.addCallback() we can expose an actionscript function and make it available to javascript. This would be helpful to have your webpage with embedded flash communicate to your flash swf file and even control it with javascript! Say we wanted to have buttons in the html page that would control an object in the flash. Communication is a two-way road so wouldn’t it be great to be able to go the other way as well, you can! That is the main function of ExternalInterface! In this example/tutorial I will explain both directions of communication with flash and javascript! Communication between flash and javascript isn’t just a myth or mystery!
Steps:
- Be sure to import flash.external.*;
- Set up the javascript to actionscript lane of your communication road. (ExternalInterface.addCallback(methodName, instance, method);)
- Write your javascript function.
- Set up the actionscript to javascript lane. (ExternalInterface.call(functionNameInJavascript);)
We will follow the text’s journey on our road of communication…
The One way: I type in ‘Johnny Appleseed’ in the html text box and press the Send Text To Flash button. The onclick javascript event finds the flash element and calls it’s function (sendTextFromHtml) and then clears the text in the html box. This function has been set up and is exposed to javascript (in actionscript lines 4-7) with the methodName ‘sendTextFromHtml’ while the method it calls is recieveTextFromHtml() in the actionscript. So ‘Johnny Appleseed’ is received as the parameter of the recieveTextFromHtml() function and is assigned to the text of the theText text box.
And back: Now I delete ‘Johnny Appleseed’ since he’s only a fable and enter ‘Paul Bunyan’ in the swf text box and press the Send From Flash to Javascript button. This calls the onRelease function associated with this button. ExternalInterface.call calls the ‘recieveTextFromFlash’ function in the javascript of the page and passes ‘Paul Bunyan’ as the parameter. The javascript function finds the html text box using getElementById() and assigns the parameter to the value of that text box!
This technique will even work if you’re not sending folklore character down the road.
Example:
View the live example here: ActionscriptJavascriptCommunication.html
NEW live example with swfobject2 works in IE! ActionscriptJavascriptCommunication2.html
Actionscript:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import flash.external.*;
//Set up Javascript to Actioscript
var methodName:String = “sendTextFromHtml”;
var instance:Object = null;
var method:Function = recieveTextFromHtml;
var wasSuccessful:Boolean = ExternalInterface.addCallback(methodName, instance, method);
//Actionscript to Javascript
//ExternalInterface.call(“recieveTextFromFlash”, _root.theText.text);
function recieveTextFromHtml(t) {
_root.theText.text = t;
}
_root.button.onRelease = function() {
ExternalInterface.call(“recieveTextFromFlash”, _root.theText.text);
_root.theText.text = “”;
}
[/cc]
Javascript:
[cc lang=”javascript” tab_size=”2″ lines=”40″]
function recieveTextFromFlash(Txt) {
document.getElementById(‘htmlText’).value = Txt;
}
[/cc]
HTML: view Source of sample page
Download:
Download all source files (.fla, .html, .swf): ActionscriptJavascriptCommunication.zip
hi,
great sollution, but in does it also works in IE ?
Good Question, half of this works in IE…
You can communicate from flash to javascript just fine. But getting from the javascript to the flash is giving me trouble. I get the “Object doesn’t support this property of method” error.
Any insight would be helpful!
i have the same problem in IE 🙁
“Object doesn’t support this property of method�
hav a flv fullscreen player,inside a html page,
in that html page one button is there,
that button should be invisible until
user click & watch half of the flv movie,
after watching that half of the movie,
that html button should be automatically active,
any idea how to do this type of thing
using javascript in flash
plz mAIL ME AT [email protected]
If I understand your question and situation correctly, You have a button in your html that you want to only be visible after a user has watched a certain amount of the movie?
I’d put a function in your player that would check to see the amount of video the user has watched, and then, once it reached 50% (or whatever percent you need) have it call a jsfunction with ExternalInterface.call(). You’d have to have this javascript function in your html page and have it hide/show the specific button… (help with that here: Javascript Code to show a hidden element)
Let me know if that helps!
hii Evan Mullins
thanks for ur reply,
i am able to trace the flv cue points,but getiing confusion in calling that function,can u help me to calling that function, just tell how do i call that function from flash to hide that html button in start & when it will reach to that particular point that html button will automatically shown, it will be very helpful for me.
////////////////////////////////////////////////
import flash.external.*;
// for calling javascript external class
// plaese writr that function here that all
/**
Requires:
– FLVPlayback component on the Stage with an instance name of my_FLVPlybk
– TextArea component on the Stage with an instance name of my_ta
*/
import mx.video.*;
my_FLVPlybk.contentPath = “http://www.helpexamples.com/flash/video/water.flv”;
my_ta.visible = false;
// create cue point object
var cuePt:Object = new Object();//create cue point object
cuePt.time = 1.444;
cuePt.name = “elapsed_time”;
cuePt.type = “actionscript”;
my_FLVPlybk.addASCuePoint(cuePt);//add AS cue point
// add 2nd AS cue point using time and name parameters
my_FLVPlybk.addASCuePoint(5.3, “elapsed_time2”);
var listenerObject:Object = new Object();
listenerObject.cuePoint = function(eventObject:Object):Void {
my_ta.text = “Cue at: ” + eventObject.info.time + ” occurred” ;
my_ta.visible = true;
};
my_FLVPlybk.addEventListener(“cuePoint”, listenerObject);
///////////// script end ///////////////////////
regards,
Neeraj
//actionscript function this goes in your flash
function call jsfunction() {
ExternalInterface.call(“showButton”);
}
//javascript function (this needs to be on the html page.
//you’ll need to give the button you want to show an id of myButton
//or change this to whatever you have… and set it’s style=”display: none;”
function showButton() {
document.getElementById(“myButton”).style.display = “”;
}
hi
The sample is nice and I changed the code to work in IE also ……the code
change the html code as follows………..
in javascript change like this
if (navigator.appName.indexOf(“Microsoft”) != -1)
{
document.getElementById(‘IEflash’).sendTextFromHtml(document.getElementById(‘htmlText’).value);
} else
{ document.getElementById(‘flash’).sendTextFromHtml(document.getElementById(‘htmlText’).value);
}
document.getElementById(“htmlText”).value = “”;
I hope this may help for some one………
Looks great! How would you go about sending data from multiple text boxes?
With ExternalInterface.call, the first argument is the name of the js function you want to call in your HTML document, and the rest are arguments you want to pass in to it. You can send many, just separate them with a comma.
so: ExternalInterface.call(“recieveTextFromFlash”, _root.theText.text);
becomes: ExternalInterface.call(“recieveTextFromFlash”, _root.theText2.text, _root.theText.text, _root.theText3.text);
Check the documentation of ExternalInterface.call from Adobe
call (ExternalInterface.call method)
public static call(methodName:String, [parameter1:Object]) : Object
Parameters
methodName:String – The name of the function to call in the container. If the function accepts parameters, they must appear following the methodName parameter.
parameter1:Object [optional] – Any parameters to be passed to the function. You can specify zero or more parameters, separating them by commas. The parameters can be of any ActionScript data type. When the call is to a JavaScript function, the ActionScript types are automatically marshalled into JavaScript types. When the call is to some other ActiveX container, the parameters are encoded in the request message.
Returns
Object – The response received from the container. If the call failed (for example if there is no such function in the container, or the interface was not available, or a recursion occurred, or there was a security issue) null is returned.
Hi saga,
Please post your full html code. Where is IEflash?
I’ve got the html/javascript submitting multiple inputs but it’s the actionscript side that I am completely clueless about.
hi,thanks for your hlep
thanks,this help me a lot
Quite clear and thorough instructions. Thanks for writing this.
Hi saga …
Can you explain where the IEFlash object is coming from on your fix for IE …
is the object embedded in a different way to flash ???
Thanks …
No such luck, original example does not work in IE7.
Can anybody help me. I need to Get value from flash to js by calling js method.
great stuff. I think this might be the solution I looking for.
I have a website in flash and html. The homepage is a flash image gallery with large picture preview related to a vertical scrolling thumbnails and a small menu at the bottom.
When you click on one of the item of the menu you are send on a html page with a css replica of the flash picture gallery.
I would like to click on a thumb located on the html page and be send back to the homepage and have the homepage gallery remember which image i’ve just clicked and display that one in my large image box.
how do i tell the flash xml image gallery which one was clicked on the html page?
cheers,
oxyde
Thanks for the comments everyone, I took a minute recently and worked with this IE issue. I tried saga’s suggestion, but it didn’t seem complete. Then I decided to update my embed codes, and I used my favorite embed option swfobject2! Doing this alone fixed the IE bug! Now we have actionscript javascript communication in any browser, IE included.
NEW live example with swfobject2 works in IE! ActionscriptJavascriptCommunication2.html
@Roland – to do that, if I understand your question correctly, you’d have to just expose an actionscript function to javascript with addCallback and have it return the value you need and call that from javascript like any other function. Good luck!
you saved me man 🙂 !!!! thank you
Object doesn’t support this property or method.
I am able to communicate from Flash to JavaScript, NO PROBLEM. However, the inverse is not true. From JavaScript to Flash, I get the above error. There is no explanation for this all code is correct. All are set, the tag is there also.
Can anyone help?
Evan – You said you fixed the codecs for that IE problem….did oyu update the zip file with that change ?
@YVR – I fixed the embed codes for IE so the javascript can now “find” the flash element on the page correctly. Nothing in the flash source changed- only the HTML. I didn’t include that in the zip file, but it is in the html page here ActionscriptJavascriptCommunication2.html, just view source. My apologies for the confusion
Wonderful…Thank you Evan for your quick reply…this helps me a lot..let me try tonight..
Hi Evan….This works perfectly as expected…but need a help on one step further down.
I just added another function in the javascript function which looks like this (hope this comments will allow me to paste JS syntax…)
function recieveTextFromFlash(Txt) {
document.getElementById(‘htmlText’).value = Txt;
DisplaySettingsPage();
}
In my Javascript page..
DisplaySettingsPage {
ajaxpage(‘products.asp’ ,’centerarea’)
}
Now when I click the Flash button it perfectly display the products.asp (which just does a select recordset from a mysql table) in the correct “centerarea” div..
Now my question is..how do I modify the code so that the resultset is not displayed in DIV but rather in a nice formated textbox in FLASH (instead of centerarea DIV) ?
-Let me know if I have confused you.
-V
Do you know if this also works with AC_RunActiveContent.js. I tried using swfobject and it blows my design apart.
thanks
@Eric – I would think so, as long as IE can still address the flash content with the getElementById(). Let us know if it does work!
@YVR – I admit, I’m confused. Not sure what you mean. You want the function coming from flash to send text back to flash? That just seems redundant…
Hi, is there a fairly easy way to get the text sent from flash
to simply send the text as a javascript call to the web page?
I’m fairly green & it would help with my learning.
Thanks
motu
hi
first sorry for my bad language
i am hamada frpm jordan i tried to write a combination with javascript and flash 8
but it doesn’t work only if it was published to web server
why i can’t do it at home ???
please reply
Is it as simple to set a cue point in a video and pass a ? variable?
I have built many flash players, but honestly I like Jeoring’s player but I would like to load different content into my side column from a database like ads that are relational to the content of the video.
I am currently looking into AMPHP but saw this post. Very informative stuff.
Can you shoot me an email if you respond please?
Evan,
Your most recent update to ActionscriptJavascriptCommunication2.html does not work in ie6. I’m still getting “null is null or not an object”. More obviously, the flash part of the page is not loading. Could you clarify this issue?
Dan
Hi all,
Very helpful site – thanks for all the effort. I have found an issue with one of your links. For the new swfObject2 example you are pointing to the incorrect location. It should be ‘/wp-content/plugins/wp-swfobject/2.0/swfobject.js’ – you have missed out the ‘2.0/’ from the url. This will fix the non-displaying example.
Thanks,
Bob
@Dan – Thanks for pointing that out
&
@Bob – Thanks man! I’ve added it and that fixed it! Should have looked at that earlier. Let me know if there are any other issues.
I can’t get externalInteface to work at all on ie if using Flash player 10 – works ok with other flash players. Anyone know a workaround or what is happening?
aaaaaaaaaaaaaaaaaaaaaaaaaa
I’m trying to use externalInterface to create a mouselistener so the mouse scroll will work when on top of the flash – as well as the spacebar and arrow keys working as well – any tips?
Thank, working fine but i want to this sample code :
ExternalInterface.call(”
function anyFunction(blah) {
blah;
blah;
blah;
return blah;
}
“);
Can anyone help me?
Thanks again!
Hi..
I am trying to do a simple thing,
ExternalInterface.call(“alert(‘Hi’)”);
This works fine if i try to run the SWF directly in the browser but doesn’t work if i try to load the player through JavaScript.
I am facing this problem in IE 8
Please help.
Hey Evan, could you please explain what code the swfobject.js file contains. I’m confused about this.
@Zshandi – The swfobject is related merely to embedding the flash swf file into the object tags correctly in each browser. It creates embed codes through javascript specific to the browser that loads the page. You’ll find more info at the google code page for swfobject: http://code.google.com/p/swfobject/wiki/documentation
best
I downloaded the swfobject and copied the example code exactly as it was, accept for the location of swfobject.js, into the source code download html page. When I tested it, it wasn’t sending text either way for some reason. But when I view the example page that’s online here, it works perfectly. I can’t tell what I might be doing wrong. Do you know what might be going wrong?
I’m using firefox3.6 btw.
Thanks!
I’d guess it’s something with your object id’s. That’s how the javascript knows what object to send the code to. Not much else i can say without looking at some code.
I figured out what was wrong. It was a problem with the security settings of flash.
I am searching for a way to interact to my database from actionscript, we are devoloping a website based on java&javascript…
do you have any idea about this how can I read and write datas to a database via actionscript…
can javascript do this?
@mine – I’d suggest taking a look at amf php for that sort of thing. http://www.amfphp.org/
For some reason, whenever I try to open ActionscriptJavascriptCommunication.fla, an alert comes up that says “Unexpected file format.” and I cant open the file.
None of the examples you’ve provided is working in IE8, it only works from AS to JS but not the other way, why? is there a fix for this?
I have some thumbnails loaded from an xml file with each one being a button to launch to corresponding shadowbox gallery. (see the portfolio section of the website) I have a var declared in my on release function which I want to use in the ExternalInterface.Call as below.
function releaseHandler() {
var galName = this[“info”].attributes.title+’Gallery’;
//trace (galName);
ExternalInterface.call(galName);
}
The trace returns the correct values but I can’t seem to use them in the ExternalInterface.call
Any hints?
@MCP – are you importing the External Interface class?
Got it sorted. Just a syntax error.
Should have double brackets around the var as follows:
ExternalInterface.call((galName));
Cheers
thank you thank you thank you ! =)
Useful but a little out of date, none of the examples worked with IE. And you have to add the allowscriptaccess : “always” to the attributes when creating the swfobject example to work too.
@Lex- of course 2.5 years is very out of date on the internet… some of the same principles apply still though. Thanks
Actually, your example works just fine on IE, but when I tried to implement it it didn’t work out.
To make it run on all browsers I had to add the
allowscriptaccess : “always”
as a param like this instead of attribute:
var params = {
allowScriptAccess: ‘always’
};
haha … loved the comment
“hi,
great sollution, but in does it also works in IE ?”
… probably not 🙂 but it’s IE
I am trying to have a flash control the display of a JavaScript button.
Here is my Actionscript 2.0 code that controls the button display.
import flash.external.*;
var method:Function = showButton;
_root.button.onRelease = function() {
ExternalInterface.call(“showButton”);
}
Here is my JavaScript function that changes the button from hidden to visible.
function showButton(){
document.getElementById(‘play’).style.visibility= “visible”;
}
This works in IE 7, but not the latest Firefox. Any help would be appreciated.
Thanks!
hi Evan,
Thanks for the great tutorial
cheer
I wanted to modify it – send text from javascript width mousover not with button! So everything worked on Chrome, but when i tried on FF it wont!
all in span
onmouseover=”getElementById(‘flash’).sendTextFromHtml(htmlText.value); document.getElementById(‘htmlText’).value = ””>MOVE MOUSE OVER HERE
i looked everywhere what can be the problem, but no answers… Please help!
Hey Onix,
I would suggest separating the code into a standalone javascript function. Sometimes putting all that on a js behavior I’ve noticed ff get finicky. Do you have it online anywhere we can see it?
best
Hi,
very interesting tutorial.
But how you can pass more than 1 parameter to function ExternalInterface.call?
( same question about function called from ExternalInterface.addCallback)
@steph le plombier
To get more than one parameter is not technically possible. But I’ve found that you can concatenate 2 params and then on the other side split the string and you’ve got your two values. Does that make sense?
You can just pass an object with all of your variables in it and you won’t need to concatenate any values.
ps thanks for the turorial
Hi Evan,
I am using the same code and trying it on chrome/firefox it is not working on neither of the browsers, can you explain why it doesn’t work on this.
Also I am trying to call a method defined in actionscript from javascript but gives an error in the browser saying “method not defined” and also am not able to call method defined in javascript from actionscript.
Hi Evan, anyone!
I have the following problem. I adapted your code (swfembed via swfobject2 etc.) and put it into my Drupal 6 website. It works fine on IE. However in Firefox v12 I have the following problem:
* the text is sent to flash after pressing the SUBMIT button twice!!!
* no errors on the site (Jscript or otherwise)
I checked in Linux etc. All Mozila based browsers show the same behaviour!?
Any quick suggestion what this might be?
Thx loads!
@Marco
Hey, I’m not sure what that would be. Is this only a ff12 issue? You’ve checked other browsers? I have seen that some browsers double the calls to callback functions before, I can’t remember the details though. Maybe do a check of a boolean value to only accept one argument in a given period of time? Let me know how it goes.
Evans …
I cannot download the source files …
The zip file gives me an error..
Could you please upload them once more…
@Saurabh – They should be working now. Best!
Hello,
please i need a help .. My project it’s about flash builder
in it’s html page there is a two text input and one button
what i want is that when the button in html page clicked, the two values in texts input to be send to mxml page in flash builder.
please how i can do that and please provide me with example code
Unexpected file format when trying to open with flash 8, any advices?
I’m not sure. You’re trying to open the fla? As file? Zip file?
I solved this by installing CS 5.5.
Hai cool site,
I have a question im trying to divide your page into a frames site on one site the html version on the other the flash version but i cant let them communicate?
Could you whip me up an example ??
thnx.
Thank you very much, it’s awesome
regards
ganesh
I have got error “Adobe Flash Player has stopped a potentially unsafe operation”…