Monday, June 12, 2006

I recently had a requirement where HTML was sent over the XMLSocket and I needed to display it within a Flex screen or browser window. The HTML I received from the server was a FULL HTML document. It had embedded 'style' tags 'class' attributes set on most of the components, and your basic 'p' and 'font' tags. Flex 2 (Beta 3) still is not able to handle HTML perfectly.

Christophe had a blog about embedding html in an iFrame, but this didn't help me since iFrames point to static HTML pages.

Here's an example of the working example where in-memory HTML is written to a new browser window:
http://www.vandalaysolutions.com/flex/html/testHTML.html

If you have a AS3 String like so:
var htmlStr : String = " this is my <b>bolded</b> and <i>italic</i> String";

Then by assigning it to the "htmlText" attribute of a mx:Text or mx:RichTextEditor tag, it will diplay correctly.

However, most HTML has far more crap in it, so you're really left with 2 options...parsing the HTML to get rid of all the crap (using RegEx) or pass the HTML off to the browser.

Using RegEx to parse everything was not a good solution for me b/c there are endless possibilites of how the HTML could appear. However, passing the HTML to the browser at first was causing problems.

The HTML that I received from the server had lots of empty lines....which the Javascript method was failing on.

var html : String = "<html>

<title>Website Title</title>

<body>
this is bold
</body>
</html>";

If you pass this to the javascript method via the ExternalInterface, you'll get the following javascript error:
Error: unterminated string literal
Source Code:
try { __flash__toXML(changeDocumentTitle("<html>

As you can see, the javascript can't handle the line break. So if you create a Regular Expression to replace all the line breaks and form feeds with an empty space, it essentially makes the HTML String one long String. Thus it can write the String to the new browser window:

//Flex method: htmlXML is of type: htmlXML : XML
var pattern:RegExp = /\n|\r|\f/gi
var htmlstr : String = htmlXML.toXMLString().replace(pattern, "");
var m:String = ExternalInterface.call("popNewWindow",htmlstr);
trace(m);//m is what the js method returns and Flex receives

//Method we need to add to the wrapper HTML page.
<script> language="JavaScript">
function popNewWindow(a) {
var generator=window.open('','name','height=550,width=700,resizable=yes,scrollbars=yes,status=yes,menubar=yes,toolbar=yes');
generator.document.write(a);
generator.document.close();
return "successful"; //passed back to Flex
}
</script>

The full code can be accessed here:
http://vandalaysolutions.com/flex/html/htmlExampleCode.zip


keywords: Flex Beta 3 adobe macromedia post html dynamic browser iframe mozilla firefox ie internet explorer ff

1 comment:

Unknown said...

The zip file doesn't appear to contain the correct mxml file. Would it be possible to add the appropriate mxml file?