javascript – Change iframe height with external src according to content height

Question:

I have an iframe where the src points to an external domain

After the content is loaded, a portion is hidden because the iframe doesn't conform to the content.

Since the iframe has an external src, I can't manipulate its content in order to get the correct height.

How to change iframe height?

Answer:

The problem was solved using "postMessage", remembering that the problem arose because I tried to access the content of an iframe where the "src" did not point to the same domain.

Basically what the code below does is send a message to the iframe after being loaded (onload) using the "postMessage".

Inside the iframe there is an event waiting for the message. When the message is received, the iframe responds (also through the "postMessage") with the height of its content.

In the parent element where the iframe was inserted, there is another event that waits for the message with the height of the content.

Script of the page where the iframe was inserted:

//Gerando o iframe
var iframe = document.createElement('iframe');
as_root.appendChild(iframe);
iframe.id = "as-root-iframe";
iframe.style.width = '100%';
iframe.style.border = 'none';
iframe.style.scrolling = 'no';
iframe.style.overflow = 'hidden';
iframe.onload = function() {
    cpframe = document.getElementById('as-root-iframe').contentWindow;
    cpframe.postMessage('iframe-ok','*');
}
iframe.src = "http://dominio.como/embed/DYaok87sd";

//evento que aguarda a mensagem com a altura do conteúdo e posteriormente altera a altura do iframe
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
    document.getElementById('as-root-iframe').style.height = e.data+'px';
},false);

Script dentro do iframe:

//evento que aguarda mensagem do elemento "pai" solicitando a altura do conteúdo
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
var h = document.getElementById('as_content').offsetHeight+50;
    window.parent.postMessage(h,"*");
},false);

It was necessary to do everything with pure Javascript because it was not possible to use frameworks like Jquery.

Scroll to Top
AllEscort