Home  >  

ExternalInterface and Code Injection Part 2

Author photo
| | Comments (0)
AddThis Social Bookmark Button

In a previous article I outlined why I needed to inject JavaScript into a page from ActionScript, now I'd like to show the implementation.

Essentially I created a new class called JSInjector. Within JSInjector I created a static function called registerPlayer. This function has an XML variable, which in turn has a CDATA area. Within this CDATA I house all of the JavaScript that I want to inject into the page.

Since it needs to be injected into the global namespace I create a single object, named something ridiculous so as to not step on anything else in the global namespace - but for the sake of clarity in this example I simply called it JSPLAYER. I then add methods to the object.

import flash.external.ExternalInterface;
 
 public class JSInjector
 {
   public function JSInjector()
   {
    }
   
   static public  function registerPlayer():void
   {
     var js:XML = <script>
      <![CDATA[
     function()
     {         
      JSPLAYER = {}
      JSPLAYER.obs = {}; // Observers
      JSPLAYER.addListener = function( eventType, callbackObj, callbackFunc){ .. }
   
   
      JSPLAYER.Rsize = function(divID, height, width)
      {
        var element = document.getElementById(divID);
        element.style.height = height + "px";
        element.style.width = width + "px";
       }
      
      JSPLAYER.OpenNewWindow = function(URLtoOpen, windowName, windowFeatures)
      {
        var newWindow=window.open(URLtoOpen, windowName, windowFeatures); 
       }
   
   ...
  }
   ]]>
     </script>
      ExternalInterface.call(js);   
    }

From there I simply call ExternalInterface and pass in the XML object, which loads the JavaScript object I created into the globalnamespace where I can then call a I would any other JavaScript function.

ExternalInterface.call("JSPLAYER.pause",true)

Read more from Tom Barker. Tom Barker's Atom feed

Comments

Leave a comment


Tag Cloud

Question of the Week: Dream App

If you had an unlimited budget and unlimited resources what application would you build and why would you build it?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.