Flash CS3 - Flash CS4

Free tutorials and scripts for all.
Actionscript 3.0

Javascript calls Actionscript

This is a discussion on Javascript calls Actionscript within the Tutorials forums, part of the Flash English category; Buenas dias ! Did you read the article actionscript calls Javascript *" In that case, Flash (via the ExternalInterface class) was calling ...


Go Back   Forum Flash CS3 Flash CS4 > Flash CS3 Flash CS4 > Flash English > Tutorials

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 03-12-07, 06:43
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,535
Rep Power: 6
Flep is on a distinguished road
Javascript calls Actionscript

Buenas dias !


Did you read the article actionscript calls Javascript*"
In that case, Flash (via the ExternalInterface class) was calling a function Javascript to create a popup in runtime.
This tutorial is the second part and we will see how to do the opposite. This time, it will be Javascript to call Actionscript.
So, I have an SWF, 2 HTML buttons and 2 images. Everything in the same HTML.
The tutorial shows how to act on the SWF from the 2 external html buttons and the 2 images still extern to the SWF.

You can take a look at the example on line following this link:

act on a SWF from external HTML buttons


I create a FLA and I save it as "main.fla".

Into which, I have a MovieClip on stage with an instance name clip_mc with a simple animation.


I create the Document Class, an AS file saved as "Main.as", implemented the following way:

Code:
package 
{
    import flash.display.MovieClip;
    import flash.external.ExternalInterface;

    public class Main extends MovieClip
	{

        public function Main()
		{
			clip_mc.stop();
			stage.frameRate=31;
			
			ExternalInterface.addCallback("sendToActionScript",fromJS);
		}
		
        private function fromJS(value:String):void
		{
			if(value=='play')
				clip_mc.play();
			else
				clip_mc.stop();
        }
    }
}
Next, I create the HTML page named main.html that contains the main.swf, 2 buttons and 2 images.
This is the code for main.html
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Javascript chiama Actionscript</title>
<script language="JavaScript">
function thisMovie(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } else {
             return document[movieName];
         }
     }
     function sendToActionScript(value) {
         thisMovie("main").sendToActionScript(value);
     }
     function sendToJavaScript(value) {
         document.forms["form1"].output.value += "ActionScript says: " + value + "\n";
     }
</script>
</head>


<div align="center">
  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
             id="main" width="500" height="375"
             codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
    <param name="movie" value="main.swf" />
    <param name="quality" value="high" />
    <param name="bgcolor" value="#869ca7" />
    <param name="allowScriptAccess" value="sameDomain" />
    <p><embed src="http://www.flepstudio.org/forum/tutorials/main.swf" quality="high" bgcolor="#869ca7"
             width="500" height="375" name="main" align="middle"
             play="true" loop="false" allowScriptAccess="sameDomain"
             type="application/x-shockwave-flash"
             pluginspage="http://www.macromedia.com/go/getflashplayer">
    </embed>
  </p></object>
  
</div>
<form name="form1" onSubmit="return false;">
         <p align="center">
           <input type="button" value="play" onClick="sendToActionScript('play');" />
           
           
             <input type="button" value="stop" onClick="sendToActionScript('stop');" />
         <p><p></p>
         <p align="center"><a href="http://www.flepstudio.org/forum/tutorials/#"><img src="http://www.flepstudio.org/forum/tutorials/pic_2.jpg" width="280" height="187" onClick="sendToActionScript('play');" /></a> <a href="http://www.flepstudio.org/forum/tutorials/#"><img src="http://www.flepstudio.org/forum/tutorials/pic_1.jpg" alt="" width="280" height="187" onClick="sendToActionScript('stop');" /></a><p><p></p>
</form>
 
Let us analyse the code

I import the needed classes
import flash.display.MovieClip;
import flash.external.ExternalInterface;

Constructor function
I stop clip_mc
clip_mc.stop();
I impost the frame rate
stage.frameRate=31;
I call the static method addCallback of the ExternalInterface class. This method registers an Actionscript function as callable from the container into which the SWF is placed. In this case, the container is main.html. So, it allows Javascript to access that function.
How to specify which function is accessible from the container"
Simple, passing to the method addCallback, 2 parameters: the first one is the name of the function Javascript that from the container will call Actionscript. The second one is the name of the Actionscript function to be called.
In this case, in main.html we have a function Javascript named sendToActionscript and an Actionscript function named fromJs.
ExternalInterface.addCallback("sendToActionScript",fromJS);

Methods
fromJS(value:String):void
I check the value passed by the Javascript (a string). If the value is "play", I start clip_mc, otherwise if the value is "stop", I stop clip_mc.
if(value=='play')
clip_mc.play();
else
clip_mc.stop();

See you soon!

Last edited by Flep; 28-08-08 at 06:43..
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #2 (permalink)  
Old 19-12-07, 02:42
Junior Member
 
Join Date: Dec 2007
Posts: 4
Rep Power: 0
ben_bjones is on a distinguished road
Re: Javascript calls Actionscript

Hi I am trying to control parts of my flash cs3 program with javascript as in calling actionscript code from javascript. I continually get the error sendToActionScript is not defined. I may be implementing the main.as file wrong but am not sure. How do you link your main.as file to the clip_mc instance in flash CS3? or to the project as a whole? On my site I have a frame.html with four java roll over buttons (home, products, about, contact) and I want each button to interact with my main.swf file which is embeded in frame.html and located in a seperate \Flash folder. I also keep my java in a seperate \Java folder as well as my css in a \Css. Is this causing the problem? If you can send me a .zip of the sample site with the .flp and .fla files included for java calling action script that would probably help a lot.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 19-12-07, 08:05
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,535
Rep Power: 6
Flep is on a distinguished road
Re: Javascript calls Actionscript

Hi and welcome

Can I see your main.fla code please ?

oh, and JS code too please
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 20-12-07, 04:57
Junior Member
 
Join Date: Dec 2007
Posts: 4
Rep Power: 0
ben_bjones is on a distinguished road
Re: Javascript calls Actionscript

--------------------------------
I have changed main to frame.as and frame.fla and added in some extra stuff from the adobe help site to check for availability of communication. I believe that the project may get heavy and need to check for commuication status while flash pages load and such. Anyways here is my frame.as, A frame in frame.fla simply says import Imports.Frame
--------------------------------

package Imports
{
import flash.display.MovieClip;
import flash.external.ExternalInterface;
import flash.events.TimerEvent;
import flash.utils.Timer;

public class Frame extends MovieClip
{

public function Frame()
{
if (ExternalInterface.available)
{
try
{
// This calls the isContainerReady() method, which in turn calls
// the container to see if Flash Player has loaded and the container
// is ready to receive calls from the SWF.
var containerReady:Boolean = isContainerReady();
if (containerReady)
{
// if the container is ready, register the SWF's functions
setupCallbacks();
}
else
{
// If the container is not ready, set up a Timer to call the
// container at 100ms intervals. Once the container responds that
// it's ready, the timer will be stopped.
var readyTimer:Timer = new Timer(100);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
}
catch (error:SecurityError)
{
trace("A SecurityError occurred: " + error.message + "\n");
throw error;
}
catch (error:Error)
{
trace("An Error occurred: " + error.message + "\n");
throw error;
}
}
else
{
trace("External interface is not available for this container.");
}
}


// ------- Private Methods -------
/**
* Calls the container's isReady() function, to check if the container is loaded
* and ready to communicate with the SWF file.
* @return Whether the container is ready to communicate with ActionScript.
*/
private function isContainerReady():Boolean
{
var result:Boolean = ExternalInterface.call("isReady");
return result;
}

/**
* Registers the appropriate ActionScript functions with the container, so that
* they can be called, and calls the "setSWFIsReady()" function in the container
* which tells the container that the SWF file is ready to receive function calls.
*/
private function setupCallbacks():void
{
// register the SWF client functions with the container
ExternalInterface.addCallback("sendToActionScript", sendToActionScript);
// notify the container that the SWF is ready to be called.
ExternalInterface.call("setSWFIsReady");
}

/**
* Handles the timer event; this function is called by the timer each
* time the elapsed time has been reached.
* The net effect is that on regular intervals this function checks
* to see if the container is ready to receive communication.
* @param event The event object for the Timer event.
*/
private function timerHandler(event:TimerEvent):void
{
// check if the container is now ready
var isReady:Boolean = isContainerReady();
if (isReady)
{
// If the container has become ready, we don't need to check anymore,
// so stop the timer.
Timer(event.target).stop();
// Set up the ActionScript methods that will be available to be
// called by the container.
setupCallbacks();
}
}

private function sendToActionScript(value:String):void
{
if(value=='play')
clip_mc.play();
else
clip_mc.stop();
}

}
}


--------------------------------
Next I will show you my frame.html and then describe where the error occurs below.
--------------------------------


--------------------------------
The main error is here


function sendToActionScript(value) {
getSWF("Frame").sendToActionScript(value);
}

and it says getSWF("Frame").sendToActionScript(value); is not a function as though SWF has not registered the sendToActionScript being a
function. The same error occured with the more simple code that I got from you as well. clip_mc is an instance of a movieclip object, should it be linked or somehow made an instance of the frame class? I believe that downloading the full javascript calls actionscript folder from you would help me to see what I'm doing wrong. esspecially to see how you have setup your main.fla and placed clip_mc in your main.

-Thanks for your time,
Ben

--------------------------------
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 20-12-07, 05:05
Junior Member
 
Join Date: Dec 2007
Posts: 4
Rep Power: 0
ben_bjones is on a distinguished road
Re: Javascript calls Actionscript

oops, here is frame.html in a comment


"


-->"
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 20-12-07, 05:11
Junior Member
 
Join Date: Dec 2007
Posts: 4
Rep Power: 0
ben_bjones is on a distinguished road
Re: Javascript calls Actionscript

I just renamed .html to .txt but here it is, how do you make this forum not parse your html and just show it raw?
Attached Files
File Type: txt Frame.txt (4.6 KB, 6 views)

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 20-12-07, 07:23
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,535
Rep Power: 6
Flep is on a distinguished road
Re: Javascript calls Actionscript

Wrap the html code into HTML tags.

Anyway, the code seems ok...

Here:
function sendToActionScript(value) {
getSWF("Frame").sendToActionScript(value);
}

the name of the SWF is Frame. Are you sure it has the capital letter ?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads

Thread Thread Starter Forum Replies Last Post
Actionscript chiama Javascript - classe ExternalInterface di Flash CS3 Flep Articoli e tutorials 6 28-12-08 13:52
Javascript chiama Actionscript 3.0 Flep Articoli e tutorials 13 05-12-08 15:40
Actionscript calls Javascript - ExternalInterface class of Flash CS3 Flep Tutorials 1 21-10-08 16:30
Interazione actionscript 2.0 - Javascript Twincpu Actionscript 3.0 base 1 18-02-08 19:43
javascript in actionscript 3.0 markuspedro Actionscript 3.0 base 4 01-02-08 11:45


All times are GMT. The time now is 16:44.

Powered by vBulletin version 3.7.4
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0 RC4
Forum SiteMap