Tuesday, August 18, 2015

Implement own CSS in htmlpanel inside Iframe in Google Web Toolkit (GWT)

Many times it happen we want to load external html file in iframe of GWT.
When we try to incorporate html file inside IFrame it become difficult to implement html file specific css. Reason parent GWT frame override the html css. To overcome it we can use following code of line.

Here we are using two static native method one is used to load iframe and another is to add our specific css to the html inside iframe.
private final native void fillIframe(IFrameElement iframe, String content) /*-{
    var doc = iframe.document;
      doc = iframe.contentDocument; // For NS6
    else if(iframe.contentWindow)
      doc = iframe.contentWindow.document; // For IE5.5 and IE6
     // Put the content in the iframe

private final native void addHeadElement(IFrameElement iframe, String cssUrl) /*-{
         setTimeout(function() {

           var body;
           if ( iframe.contentDocument ) {
             // FF
             iframe.contentDocument.designMode= "On";
             body= iframe.contentDocument.body;
           else if ( iframe.contentWindow ) {
             // IE
             body = iframe.contentWindow.document.body;

           if (body == null) {

           body.className = "custom-body-classname";
           var head = body.previousSibling;
           if(head == null) {
             head = iframe.contentWindow.document.createElement("head");

             iframe.contentWindow.document.childNodes[0].insertBefore(head, body);
           var fileref = iframe.contentWindow.document.createElement("link");
           fileref.setAttribute("rel", "stylesheet");
           fileref.setAttribute("type", "text/css");
           fileref.setAttribute("href", cssUrl);
         }, 50);

Make sure that we need to  call this above two static native method before using iframe concept.

This is the code which we use to insert html code in our IFrame.

final HTML htmlPanel = new HTML("

This is siddharatha

       FlowPanel innerBox = new FlowPanel() {
           protected void onLoad() {
               // Fill the IFrame with the content html
               fillIframe(iframe, htmlPanel.getHTML());
               // Add a HEAD element to the IFrame with the appropriate CSS
               addHeadElement(iframe, "siddhu.css");


No comments: