views:

1008

answers:

1

How do I set the focus on a SWF embedded in a page using Javascript? I tried to use the usual method but it doesnt seem to work...

+2  A: 

There are known issues with focus management and Flash in Firefox, unfortunately.

Here's an article that explains one approach that could work for you, though; the upshot is that you can use JavaScript and flash.external.ExternalInterface to notify the Flash file of keyboard activity until the Flash control gains focus normally. I've implemented an approach like this before and it works just fine; for example, my own solution looked something like this, in the containing HTML page:

<script language="javascript">

    if (navigator.appName.indexOf("Microsoft") != -1)
    {
     document.attachEvent("onkeydown", ieKeyHandler);
     window.attachEvent("onkeydown", ieKeyHandler);

     function ieKeyHandler(event)
     {  
      sendToFlash(event.keyCode);
     }  
    }
    else
    {
     document.onkeydown = function(e)
     {  
      sendToFlash(e.keyCode);
     }
    }

    function sendToFlash(s)
    {  
     var flashCtl = thisMovie("yourFlashObjectID");
     flashCtl.callIntoFlashFromJavascript(s);   
    }

    function thisMovie(movieName)
    {
     if (navigator.appName.indexOf("Microsoft") != -1)   
     {
      return window[movieName];
     }
     else
     {
      return document[movieName];
     }
    }

</script>

... and then in the Flash file, you could simply define an ExternalInterface callback handler for a function called callIntoFlashFromJavascript, and pass the string argument into your text control. It's a bit heavy-handed, admittedly, but it works.

See my answer to this question as well for an end-to-end example of using ExternalInterface with JavaScript. Hope it helps!

Christian Nunciato