Avg. Rating 5.0

Problem

It is necessary to hide JavaScript code in the Flash / Flex application to obtain a SWF file

Solution

JSInterface will be used to download the JavaScript file

Detailed explanation

To integrate any file in the Flex application by using metatag [Embed] indicating myme-type as application / octet-stream. In this way you can save your JavaScript code in the Flex application, but you can work with this code only if you download it in your browser in HTML document. To download the code, use the library JSnterface.

For example, using the popular JavaScript library jQuery:

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"

preinitialize="{initJSInterface()}"

creationComplete="{creationCompleteHandler(event)}">

 <mx:Script>

  <![CDATA[

   import flash.utils.setInterval;

   import aw.external.JSInterface;

   // Embed jQuery library into Flex application

   [Embed(source="jquery-1.2.6.js",mimeType="application/octet-stream")]

   static private const J_QUERY_SCRIPT:Class;

   protected function initJSInterface():void{

    JSInterface.initialize();

    // Get embeded code as text

    var data:ByteArray = new J_QUERY_SCRIPT();

    data.position = 0;

    // Insert jQuery into HTML as virtual - without creating <SCRIPT> container

    JSInterface.pushJavaScript(data.readUTFBytes(data.length), '', true);

   }

   private var $:Function;

   protected function creationCompleteHandler(event:Event):void{

    // Now you can use jQuery through JSInterface or ExternalInterface

    $ = JSInterface.window.$;

    trace($('body'));

    trace($('embed')[0].src);

   }

  ]]>

 </mx:Script>

</mx:Application>

 

In this example, the jQuery code was integrated into Flex application, and loaded into an HTML page with the help of JSInterface.pushJavaScript(). This way you can protect the supplied JavaScript code from unsanctioned access and to pack the entire set of JavaScript/CSS files into one SWF package. JSInterface implements the same method for CSS - JSInterface.pushCSS ().

Look into attached archive file for example Flex Builder project.

Visit the JSInterface official site.

PushJavaScriptFromFlex.zip
[Example Flex Builder project]
Report abuse

Related recipes