2

Here is my testing.html:

<html>
<meta charset="utf-8">
<script>
window.onload = function() {
    var a = document.getElementById("divid");
    var ifr = document.createElement('iframe');
    a.appendChild(ifr);
    ifr.contentDocument.body.style.cssText = (
      'margin: 0px;' +
      'padding: 0px;' +
      'height: 100%;' +
      'width: 100%;');
}
</script>

<head></head>
<body>
<div id="divid"/>
</body>
</html>

Here ifr.contentDocument.body.style.cssText = (...) works fine on chrome but not on Firefox. Is it a firefox bug? Is there any workaround?

Found workaround: Looks like there is a weird race bug in firefox. The following workaround with setTimeout will make this work fine as shown below:

<html>
<meta charset="utf-8">
<script>
window.onload = function() {
    var a = document.getElementById("divid");
    var ifr = document.createElement('iframe');
    ifr.id = "fid";
    a.appendChild(ifr);
    setTimeout (function() {
        ifr.contentDocument.body.style.cssText = (
        'margin: 0px;' +
        'padding: 0px;' +
        'height: 100%;' +
        'width: 100%;');
    }, 100);
}
</script>

<head></head>
<body>
<div id="divid"/>
</body>
</html>
Krishna Srinivas
  • 1,620
  • 1
  • 13
  • 19
  • Here is exactly what you need: http://stackoverflow.com/questions/926916/how-to-get-the-bodys-content-of-an-iframe-in-javascript – Ivan Chernykh May 05 '13 at 06:01

3 Answers3

6

When you append the iframe in Firefox it starts loading about:blank in the iframe, asynchronously. Then you touch the document, so it has to synchronously create an about:blank document in there, and you modify it. Then the async load completes and replaces the document you modified.

Waiting for the load event on the frame to fire before modifying it would work.

Boris Zbarsky
  • 34,758
  • 5
  • 52
  • 55
1

try this:

 ifr.contentDocument.getElementsByTagName('body')[0].style.cssText = (
  'margin: 0px;' +
  'padding: 0px;' +
  'height: 100%;' +
  'width: 100%;');

also

<div id="divid"> </div>
Prakash GPz
  • 1,675
  • 4
  • 16
  • 27
0

To expand on Boris' answer, Here be Dragons!

Although this will get Firefox working, it will currently also break Chrome, Opera, Safari, and all their mobile counterparts, as they will NOT throw the 'onLoad' event as on these platforms, the iframe sits idle until used.

You will need to make this a Firefox only exception. Luckily due to Firefox's frustrating lack of features, its pretty easy to tell them apart. Just look for something the rest of the internet has but Firefox does not, or vice versa.

if(typeof InstallTrigger !== 'undefined'){  //if ie, wait sorry, firefox
    iframe.onload = function(){
        iframe.contentDocument.body.appendChild(contents);
    }
}else{
    iframe.contentDocument.body.appendChild(contents);
} 

Firefox, The new Internet Explorer

kaioker2
  • 297
  • 3
  • 11