07Mar

[AS 3] Loading an External .HTML File

1 comment so far

A little snippet of code to pull in an html file and place the html content to a text field.

package
{
	import flash.display.Sprite;
	import flash.text.*;
	import flash.net.*;
	import flash.events.*;

	public class loadHTML extends Sprite
	{
		private var txtField:TextField;
		private var HTMLData:String;
		private var myHTMLFile:URLLoader;

		public function loadHTML()
		{
			myHTMLFile = new URLLoader();
			myHTMLFile.addEventListener(Event.COMPLETE, onLoadHTML, false, 0, true);
			myHTMLFile.addEventListener(IOErrorEvent.IO_ERROR, ioError, false, 0, true);
			myHTMLFile.load(new URLRequest("/path/to/html/file"));
		}

		private function onLoadHTML(e:Event):void
		{
			HTMLData = e.target.data;
			initTextField();
		}

		private function initTextField():void
		{
			txtField = new TextField();
			txtField.x = txtField.y = 20;
			txtField.width = stage.stageWidth;
			txtField.multiline = true;
			txtField.wordWrap = true;
			txtField.autoSize = TextFieldAutoSize.LEFT;
			txtField.selectable = false;
			txtField.htmlText = HTMLData;

			addChild(txtField);

			myHTMLFile.removeEventListener(Event.COMPLETE, onLoadHTML);
			myHTMLFile.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
		}

		private function ioError(e:IOErrorEvent):void
		{
			trace ("Error: File " + e.text + " could not be loaded");
		}
	}
}

Share/Save/Bookmark

Friday, March 7th, 2008 at 10:52 am and is filed under Actionscript 3, Flash Text / HTML / CSS. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “[AS 3] Loading an External .HTML File”

  1. Posted by Oli 5th October, 2008 at 11:31 pm

    Good code, but a bit long. I have some problems with any solutions I found on the net.
    Also trying to load an HTML File. The content is at the moment pretty simple:

    This is some Test code.

    Something like this.
    But when I try to display it within a TextField (myTextField.htmlText = [html file content]) it adds some css text also. Looks like this:

    p.p1 {margin:0.0px 0.0px 0.0px 0.0px font:12.0px Helvetica}
    This is some Test code.

    So it doesn’t translate the html at all and adds some css in the output. How do I load this file?? I also added the dataFormat text to the URLLoader… nothing different… :/

Leave a reply