2011-04-09 34 views
28

Estoy buscando una buena secuencia de comandos de cambio de tamaño de iframe entre dominios que ajuste su altura en función de su contenido. También tengo acceso a html/css para la fuente del iframe. ¿Hay alguno por ahí?cross-domain iframe resizer?

+0

check out esta solución fácil en su lugar: http: // stackoverflow.com/questions/7024574/get-and-set-iframe-content-height-auto-resize-dynamically-easy-solution-expanding – Paul

+1

¿Soy yo o todas estas respuestas requieren que agregue un script a la página * externa *? ? – redben

Respuesta

1

EasyXDM puede hacer precisamente esto :) This blog pos t explica la esencia de la misma

+0

Acabo de echar un vistazo y parece estar fuera de mi experiencia. – J82

+0

Consulte http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/ para obtener una explicación: realmente no hay una manera más fácil. –

31

Si los usuarios están en los navegadores modernos, puede resolver esto con bastante facilidad con postMessage in HTML5. Aquí hay una solución rápida que funciona bien:

La página de iframe:

<!DOCTYPE html> 
<head> 
</head> 
<body onload="parent.postMessage(document.body.scrollHeight, 'http://target.domain.com');"> 
    <h3>Got post?</h3> 
    <p>Lots of stuff here which will be inside the iframe.</p> 
</body> 
</html> 

La página original que contiene el iframe (y le gustaría conocer su altura):

<script type="text/javascript"> 
    function resizeCrossDomainIframe(id, other_domain) { 
    var iframe = document.getElementById(id); 
    window.addEventListener('message', function(event) { 
     if (event.origin !== other_domain) return; // only accept messages from the specified domain 
     if (isNaN(event.data)) return; // only accept something which can be parsed as a number 
     var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar 
     iframe.height = height + "px"; 
    }, false); 
    } 
</script> 
<iframe src='http://example.com/page_containing_iframe.html' id="my_iframe" onload="resizeCrossDomainIframe('my_iframe', 'http://example.com');"> 
</iframe> 
+1

Me funcionó; El único inconveniente es que el sitio iFramed remoto también necesita ser editado y esto no funcionará si no se puede editar –

+0

Probé esto en Chrome (versión 56.0.2924.87) sin éxito. No obtenga ningún error, pero tampoco se realiza ningún cambio de tamaño. – Stefan

0

Después de algunas investigaciones, terminé usando el mecanismo de paso de mensajes de html5 incluido en un jQuery pluging que lo hace compatible con navegadores más antiguos usando varios métodos (algunos de ellos descritos en este hilo).

La solución final es muy simple.

En el host (padre) página:

// executes when a message is received from the iframe, to adjust 
// the iframe's height 
    $.receiveMessage(
     function(event){ 
      $('my_iframe').css({ 
       height: event.data 
      }); 
    }); 

// Please note this function could also verify event.origin and other security-related checks. 

En la página iframe:

$(function(){ 

    // Sends a message to the parent window to tell it the height of the 
    // iframe's body 

    var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined); 

    $.postMessage(
     $('body').outerHeight(true) + 'px', 
     '*', 
     target 
    ); 

}); 

He probado esto en Chrome 13+, Firefox 3.6+, Internet Explorer 7 , 8 y 9 en XP y W7, safari en OSX y W7. ;)

0

siguiente código que funcionó para mí:

var iframe = document.getElementById(id); 
iframe.height = iframe.contentDocument.body.scrollHeight; 

probado en Opera 11, IE 8 9, FF 8, Chrome 16

+10

Esto solo funciona si el iframe src está en el mismo dominio que el padre. – jessica

1

El primer guión en esta página - el uso de postMessage en HTML5 - también funciona para iframes en dispositivos móviles - cambiando el tamaño del iframe al contenido - por ejemplo, distribuyendo dominios cruzados - puede desplazarse fácilmente en iphones o android, de una manera que no es posible con iframes de lo contrario

0

tengo una solución totalmente diferente para cruzar iframe cambio de tamaño de dominio. Implica obtener una copia de la página de destino que colocará en su iframe, lo escribirá localmente, luego colocará esa copia en su iframe y cambiará el tamaño según el mismo acceso de dominio al dom dentro del marco.

un ejemplo sigue:

<?php 
      if(isset($_GET['html'])) $blogpagehtml = file_get_contents(urldecode($_GET['html'])); 
      else $blogpagehtml = file_get_contents('http://r****d.wordpress.com/'); 
      $doc = new DOMDocument(); 
      libxml_use_internal_errors(true); 
      $doc->loadHTML($blogpagehtml); 
      libxml_use_internal_errors(false); 
      $anchors = $doc->getElementsByTagName("a"); 
      foreach($anchors as $anchor) { 
       $anchorlink=$anchor->getAttribute("href"); 
       if(strpos($anchorlink,"http://r****d.wordpress")===false) $anchor->setAttribute("target","_top"); 
       else $anchor->setAttribute("href","formatimportedblog.php?html=".urlencode($anchorlink));   
      } 
      $newblogpagehtml = $doc->saveHTML(); 
      $token = rand(0,50); 
      file_put_contents('tempblog'.$token.'.html',$newblogpagehtml); 


?> 

      <iframe id='iframe1' style='width:970px;margin:0 auto;' src='tempblog<?php echo $token; ?>.html' frameborder="0" scrolling="no" onLoad="autoResize('iframe1');" height="5600"></iframe>