Friday, May 20, 2011

HTML in AIR: Part 9

Today we will start learning about using Javascript and Actionscript together with an HTMLLoader object.

The following few tutorials will require some at least basic Javascript and HTML knowledge.

When the HTML content is loaded into a HTMLLoader object, all the HTML DOM (Document Object Model) model becomes accessible through the window property. Using the DOM, we can refer to any elements of the HTML page through this window property the same way as we would do that using the window property for JavaScript.

There's one thing to note, though - we can only do that with AS3 once the page has finished loading. We can see when it's loaded by adding an Event.COMPLETE event listener for the HTMLLoader object.

Let's see how this works with examples. Let's create a simple HTML page with a button, which alerts a text string.

<html>
<script type="text/javascript">
var mytext = "This is some text";
function showText(){
alert(mytext);
}
</script>
<body>
<input type="button" onclick="showText()" value="Alert">
</body>
</html>

I've saved this HTML file as air_js.html. You can test it - when you click the only button on the page, a new window will pop up with the text message that we've written.

Now I'm going to make a new AIR project and write some AS3 code.

Firstly, create the HTMLLoader object, load the page and then add a listener for the complete event:

var myHtml:HTMLLoader = new HTMLLoader();
myHtml.width = 550;
myHtml.height = 400;
myHtml.load(new URLRequest("air_js.html"));
addChild(myHtml);
myHtml.addEventListener(Event.COMPLETE, onload);

Now, we will read the variable in our Javascript code and then apply that text to the window's title. To do that, we can access the variable through the DOM object (using the window property of our loader).

function onload(Event):void
{
stage.nativeWindow.title = myHtml.window.mytext;
}

We can not only read, but also write variables this way:

function onload(Event):void
{
myHtml.window.mytext = "Hello! This text is loaded from AIR";
}

With that code, the next time you load the HTML page and click the button, it will alert you the new text which we've passed using AS3 code.

That's all for now.

Thanks for reading!

Related:

HTML in AIR: Part 1
HTML in AIR: Part 2
HTML in AIR: Part 3
HTML in AIR: Part 4
HTML in AIR: Part 5
HTML in AIR: Part 6
HTML in AIR: Part 7
HTML in AIR: Part 8
HTML in AIR: Part 10
HTML in AIR: Part 11
HTML in AIR: Part 12
HTML in AIR: Part 13
HTML in AIR: Part 14
HTML in AIR: Part 15
HTML in AIR: Part 16
HTML in AIR: Part 17

No comments:

Post a Comment