views:

110

answers:

2

I have a flash movie that requires some JavaScript from an include file but I'd like to be able to embed it anywhere without requiring a script tag.

Is there a way to include an external JavaScript file using the ExternalInterface library so I can call the methods in the JavaScript include file later?

Thanks!

+3  A: 

everything javascript can do, can be done with externallinterface. i think the best way would be to port the js script to ac.

this is how you can include a tag:

ExternalInterface.call("document.getElementsByTagName('head')[0].appendChild(document.createElement('script'))");
ExternalInterface.call("document.getElementsByTagName('script')[document.getElementsByTagName('head')[0].getElementsByTagName('script').length-1].setAttribute('type', 'text/javascript')");
ExternalInterface.call("document.getElementsByTagName('script')[document.getElementsByTagName('head')[0].getElementsByTagName('script').length-1].setAttribute('src', 'http://your.server/your.js')");
antpaw
+3  A: 

Not many people realize it, but you can write inline Javascript in your .as files, and even pass in values, like so:

var someVarInAS : String = 'foo';
var someOtherVarInAS : int = 10;
var jsXML : XML = 
<script type="text/javascript">
    var someVarInJS = '{someVarInAS}';
    var someOtherVarInJS = {someOtherVarInAS};
    <![CDATA[
     //here be code
     alert( 'this comes from flash: ' + someVarInJS + ', ' + someOtherVarInJS );
    ]]>
</script>;


ExternalInterface.call( "function js_" + ( new Date().getTime() ) + "(){ " + jsXML + " }" );

A few things to note:

  1. the {} inside the javascript code will translate to the value of whatever variable you put in between
  2. the cdata section enables you to write whatever javascript code you want, otherwise the compiler can complain.
  3. All javascript code called through externalinterface should be placed in a named function, otherwise it will not work in a few browsers. In this code snippet I employ a little trick (new Date().getTime()) to ensure the function always has a unique name and can't conflict with another one with possibly the same name.
  4. don't forget the ; behind </script> it tells the compiler your javascript ends there
Creynders