A recent flex project I have been working on requires users to log-in using a given username and password combination via a form in order to access a non-public CMS. When the app first loads, the user is presented with a flash login form, in which we have pre-focused the username field.
Natural user response when faced with a focused text field is to just start typing away and expect full keyboard control over the form.

This does not happen with flash 😡

Usually if you want to give focus to an HTML element, you just call the focus() method directly on the object, but not all browsers support this – in fact Chrome and Safari will ignore focus requests. (more info here)

To solve this issue, I setup a keyboard proxy javascript class that acts as a fallback in case the auto focusing doesn’t operate correctly.
The logic flow is as follows:

  • The first thing we do it set up a flag in the Flex App that is activated when the flash receives focus and the StageEnter event.
  • When the Flex is loaded and ready, it attempts to draw focus to itself via ExternalInterface.
  • The app then waits a tenth of a second and checks to see if the focus flag has been activated.
    If so, then flash has keyboard focus ok, so we should leave well alone!
  • If not, then activate the KeyboardProxy so that all keyboard input is trapped by the browser and piped into the flash app.
  • Finally, whenever the user clicks and focuses the app, our StageEnter event will fire and automatically disable the KeyboardProxy

Within the KeyboardProxy javascript class, we simply trap keyboard input and pipe it directly into the Flex. Using ExternalInterface, we can expose a method to javascript and use it to send key information into flash and reproduce native Keyboard Events.

Actionscript Class:

Javascript Class:

..and that’s about it. All I needed to do from here is add instantiate the BrowserKeyboardProxy class and add a listener for KeyboardEvents coming from it. The event carried the KeyCode, which was translated into a character using String.fromCharCode() and then injected into the input text field.

One thing to watch is if the proxy isn’t disabled when the flash actually gains focus, you’ll get duplicated keyboard input and undesirable effects.

Add a little finesse when dealing with backspace, delete, arrow and tab keys and the user won’t ever notice the difference! 🙂