Once in a while, even a blind squirrel finds a nut.
Embedding HTML Document in an IFRAME With GWT
While working on a recent project in GWT, I needed to embed a full HTML document inside an IFRAME. And I didn’t want to specify a remote URL for the IFRAME - I actually wanted to shove the HTML content directly into the IFRAME.
Initially I thought it was trivial: create an IFrameElement and call setInnerHTML.
Unfortunately, that doesn’t work. It doesn’t cause any errors, but it doesn’t actually fill in the iframe. Instead, you have to use native javascript to write into the document object for the iframe:
12345678910111213
privatefinalnativevoidfillIframe(IFrameElementiframe,Stringcontent){vardoc=iframe.document;if(iframe.contentDocument)doc=iframe.contentDocument;// For NS6elseif(iframe.contentWindow)doc=iframe.contentWindow.document;// For IE5.5 and IE6// Put the content in the iframedoc.open();doc.writeln(content);doc.close();};
Voila! However, one of the side effects is that the iframe doesn’t include any CSS unless your embedded HTML references a stylesheet. If you want to manually add a reference to a specific stylesheet, you can do that through native javascript as well:
There’s still one more problem. You can’t use either of native methods until the IFRAME element has been attached to the DOM. The easiest way around this is to add the IFRAME element to a panel and over the onLoad() method for the panel:
1234567891011121314
finalIFrameElementiframe=Document.get().createIFrameElement();FlowPanelinnerBox=newFlowPanel(){@OverrideprotectedvoidonLoad(){super.onLoad();// Fill the IFrame with the content htmlfillIframe(iframe,contentHtml);// Add a HEAD element to the IFrame with the appropriate CSSaddHeadElement(iframe,cssUrl);}};innerBox.getElement().appendChild(iframe);