Monday, March 28, 2005

Dynamic old-school IFRAMEs

Three years ago I lifted the following code for dynamically creating an IFRAME from Eric Costello's ADC article, Remote Scripting With IFRAME, and I've used some variation of it for years in my own development work. I modified it a bit since its original purpose was as part of a remote scripting engine; all I wanted was the IFRAME-generation code. Check out the crazy bit where Eric "fakes up" the IFRAME for IE5.

It's a wicked piece of code for the time it was written. It's one of those techniques that you can only learn about after several hours of doing — that is, messing around in a browser trying to get stuff to work. There's just no textbook for this kind of stuff.

Dunno if it works in Safari, Konqueror or Opera, although I'd love to hear if it does or doesn't.


/*
dynamic IFRAME code
original JS by Eric Costello (glish.com) for ADC
http://developer.apple.com/internet/webcontent/iframe.html
*/

var iframe, iframeDocument;
var iframeID = "MyHiddenIFrame";

if (document.createElement) {   
  try {
   
    var tempIFrame = document.createElement('iframe');
    tempIFrame.setAttribute('id',iframeID);
    tempIFrame.style.border = '0px';
    tempIFrame.style.width = '0px';
    tempIFrame.style.height = '0px';
    iframe = document.body.appendChild(tempIFrame);
      
    if (document.frames) {
      
      /* IE5 Mac only allows access to the document
      of the IFrame through frames collection */
        
      iframe = document.frames[iframeID];
    }
      
  } catch (ex) {
    
    /* This part is CRAZY! -- scottandrew */

    /* IE5 PC does not allow dynamic creation and 
    manipulation of an iframe object. Instead, we'll fake
    it up by creating our own objects. */
      
    var iframeHTML = '\<iframe id="' + iframeID + '"';
    iframeHTML += ' style="border:0px; width:0px; height:0px;';
    iframeHTML += '"><\/iframe>';
    document.body.innerHTML += iframeHTML;
    iframe = new Object();
    iframe.document = new Object();
    iframe.document.location = new Object();
    iframe.document.location.iframe = 
      document.getElementById(iframeID);
    iframe.document.location.replace = 
      function(location) {
        this.iframe.src = location;
      }
  }
  
  if (iframe.contentDocument) { // For NS6
    iframeDocument = iframe.contentDocument; 
  } else if (iframe.contentWindow) { // For IE5.5 and IE6
    iframeDocument = iframe.contentWindow.document;
  } else if (iframe.document) { // For IE5
    iframeDocument = iframe.document;
  } else { // damn!
    alert("Error: could not find IFRAME document");
  }
}

1 Comments:

At 1:01 PM, Blogger Unknown said...

This comment has been removed by the author.

 

Post a Comment

<< Home