Flex Component that injects Javascript in HTML host

I know subject line is confusing but I am not able to think of a better one.

I have written a Adobe Flex 2.0 component(JavaScript.as), which can be used as MXML tag in Flex 2.0 applications. You can write JavaScript code as text of this MXML tag. When your application loads, all that JavaScript code would be injected host HTML’s DOM.

Confused? Let’s look at some examples.

Sample MXML application using this component (test.mxml):-

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="com.abdulqabiz.utils.*"  width="100%" height="100%">
var myName = "Abdul Qabiz";
function saySomething (str)
alert (str);
function sayHelloWorld ()
alert ("Hello World!");
import flash.external.ExternalInterface;
private function invokeSayHelloWorld ()
ExternalInterface.call ("sayHelloWorld");
<mx:Button label="invoke javascript sayHelloWorld () function" click="invokeSayHelloWorld ()"/>

HTML code that embeds test.swf(output of above code):-

<!-- swfobject -->
<script type="text/javascript" src="http://blog.deconcept.com/swfobject/swfobject_source.js"></script>
<div id="flashcontent" class="playerContent" >You don't have Flash Player 9.</div>
<script type="text/javascript">
var swfObj = new SWFObject ("JavaScriptComponentTest.swf","JavaScriptComponentTest", "300", "300", "9", "#C0D4DD", true);
<a href="javascript:void(0)" onclick="saySomething ('hey')" >invoke saySomething ()</a><br />
<a href="javascript:void(0)" onclick="sayHelloWorld ()" >invoke sayHelloWorld ()</a><br />
<a href="javascript:void(0)" onclick="alert (myName);">show myName </a><br />

See an example Or Download (zip 133kb includes the SWF).

The code is available under the MIT license.

Disclaimer: I have only tested this in FireFox on Windows. So please drop a comment, if doesn’t work in your system.

March 6, 2007 – Fixed a bug, which popped-up after I implemented comment removal feature. Thanks to Joan for point it out.
March 5, 2007 – Library has been updated, it can now handle comments in JavaScript code. It would basically remove all comments before injecting it in HTML container.