Setting HTML Focus From Flash or Flex Content in AIR

It is possible to set HTML focus from Flash or Flex content in AIR, but it takes a little finessing. The key is to focus the HTMLLoader before setting focus to something inside the HTMLLoader. The code below shows an HTML text input getting focus when the document loads, and it shows how to set focus on-demand from Flash or Flex. I’ll let the code explain the rest:

Flex code:

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="onApplicationComplete();"><mx:Script><![CDATA[private function onApplicationComplete():void{this.stage.focus = html.htmlLoader;html.location = "form.html?t=" + new Date().time; // Prevent cacheing while testing}private function onSetFocus():void{this.stage.focus = html.htmlLoader;this.html.htmlLoader.window.setFocus();}]]></mx:Script><mx:VBox width="100%" height="100%"><mx:HTML id="html" width="100%" height="100%"/><mx:Button label="Set focus from Flash" click="onSetFocus();"/></mx:VBox></mx:WindowedApplication>

HTML code:

<html><head><script type="text/javascript">function setFocus() {var myText = document.getElementById('myText');myText.focus();}</script></head><body onLoad="setFocus();"><form id="myForm"><input type="text" id="myText" width="200"/><br/><button onClick="setFocus();">Set focus from HTML</button></form></body></html>