Resize Cross Domain Iframe Height [duplicate] - javascript

This question already has answers here:
Resizing an iframe based on content
(26 answers)
How to get height of iframe cross domain
(2 answers)
Closed 2 years ago.
I'm trying to change the iframe height parameter to the same px of the page being loaded within the iframe. The page that's being loaded in the iframe is coming from another domain.
Different pages will be loaded up inside of the iframe causing the height of the iframe content to change, So I will need to grab the iframe content height and apply it to the iframe height parameter.
Here a example of what im talking about: http://jsfiddle.net/R7Yz9/3/
<div class="site">Amazon </div>
<div class="site">Cnn </div>
<div class="site">Wikipedia </div>
<iframe id="source" src="http://amazon.com/" frameborder="0" scrolling="no" width="100%" height="100%"></iframe>
.
$(document).ready(function() {
var iframe = $( "#source" );
$( "a[target=_top]" ).click( function(){
iframe.attr( "src", this.href );
return false;
});
});

It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.
https://github.com/davidjbradshaw/iframe-resizer
It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.
Works in all modern browsers and IE8 upwards.

Minimum crossdomain set I've used for embedding fitted single iframe on a page.
On embedding page (containing iframe):
<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen for a message from the iframe.
eventer(messageEvent, function(e) {
if (isNaN(e.data)) return;
// replace #sizetracker with what ever what ever iframe id you need
document.getElementById('sizetracker').style.height = e.data + 'px';
}, false);
</script>
On embedded page (iframe):
<script type="text/javascript">
function sendHeight()
{
if(parent.postMessage)
{
// replace #wrapper with element that contains
// actual page content
var height= document.getElementById('wrapper').offsetHeight;
parent.postMessage(height, '*');
}
}
// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen for a message from the iframe.
eventer(messageEvent, function(e) {
if (isNaN(e.data)) return;
sendHeight();
},
false);
</script>

You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377
yourotherdomain.html
<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
// Size the parent iFrame
function iframeResize() {
var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
parent.postMessage("resize::"+height,"*");
}
$(document).ready(function() {
// Resize iframe
setInterval(iframeResize, 1000);
});
</script>
your website with iframe
<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
// Listen for messages sent from the iFrame
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// If the message is a resize frame request
if (e.data.indexOf('resize::') != -1) {
var height = e.data.replace('resize::', '');
document.getElementById('edh-iframe').style.height = height+'px';
}
} ,false);
</script>

If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe container anytime the height of the framed content changes.
Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).
window.addEventListener("load", function(){
if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe
send_height_to_parent_function = function(){
var height = document.getElementsByTagName("html")[0].clientHeight;
//console.log("Sending height as " + height + "px");
parent.postMessage({"height" : height }, "*");
}
// send message to parent about height updates
send_height_to_parent_function(); //whenever the page is loaded
window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
var observer = new MutationObserver(send_height_to_parent_function); // whenever DOM changes PT1
var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
observer.observe(window.document, config); // PT3
});
Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.
<script>
window.addEventListener("message", function(e){
var this_frame = document.getElementById("healthy_behavior_iframe");
if (this_frame.contentWindow === e.source) {
this_frame.height = e.data.height + "px";
this_frame.style.height = e.data.height + "px";
}
})
</script>

There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example
<code>
<?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
<?php echo $output; ?>
</div>
<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>
<script>
if(window.attachEvent) {
window.attachEvent('onload', iframeResizer);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
iframeResizer(evt);
};
window.onload = newonload;
} else {
window.onload = iframeResizer;
}
}
function iframeResizer(){
var result = document.getElementById("iframediv").offsetHeight;
document.getElementById("iframe").style.height = result;
document.getElementById("iframediv").style.display = 'none';
document.getElementById("iframe").style.display = 'inline';
}
</script>
</code>

Related

how to set iframe height dynamically depending on its content

I want to set the iframe height depending on the content height, here below code is working for local links, but i want to do it on dynamically.
please help.
<iframe id="frameDemo" src="https://myvook.blogspot.com"></iframe>
<script>
$(document).ready(function() {
$( "#frameDemo" ).on('load', function() {
var mydiv = $(this).contents().find("body");
var h = mydiv.height();
$("#frameDemo").height(h);
});
});
Following up with what Rory said, it's not possible to set the iframe height before before the iframe has been loaded since you'll be pulling content from another domain.
However, it is possible to set the height of the iframe after you've downloaded the content. Here is how I've tackled it:
function noteContentIframeLoaded(iframeId) {
// See http://stackoverflow.com/a/5788723 for how to implement this function
var iframeElement = $("#" + iframeId)[0];
setTimeout(function() {
setIframeHeight(iframeElement);
}, 10);
}
function setIframeHeight(iframe) {
if (iframe) {
if (iframe.contentWindow || iframe.contentDocument) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height = (iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight);
}
}
}
}

Is it safe to use '*' as the origin of a message from inside an iframe?

The problem was, that I had an <iframe> with dynamically changing content. I couldn't find any other way to dynamically change the height of the <iframe> element than sending new height each time when it changes to the bloggers website by parent.postMessage. The solution works (maybe it can help others, but the thing is that I'm not sure if I have done it in a safe way.
I just want to ask if it's safe to use window.parent.postMessage('Some message', '*') in that way?
Embeded site:
<script type="text/javascript">
var framesHeight = 0;
setInterval(function(){
var newFramesHeight = window.document.getElementsByTagName('html')[0].offsetHeight;
if (newFramesHeight !== framesHeight) {
window.parent.postMessage(newFramesHeight, '*');
framesHeight = newFramesHeight;
}
}, 500);
</script>
As you can see, each time when the hight changes I send a new message.
On the bloggers website I want to embed this:
<script>
window.addEventListener('message', function (evt) {
if (evt.origin === 'http://mypage.com' && !isNaN(evt.data)) {
document.getElementById('embedID').style.height = evt.data+'px';
}
}, false);
</script>
<iframe id="embedID" src="http://mypage.com/embed/11" frameborder="0" style="width: 100%; height: 100%;" scrolling="no"></iframe>

Edit iframe dynamic content

I'm trying to edit the size of dinamic content generated on external url.
There's my code:
HTML:
<div id="movie">
<iframe name="ifr" id="ifr" src="http://zeyu.ucoz.es/directvenvio.html" width="100%" height="480" frameborder="0" scrolling="no"></iframe>
</div>
In this source url, there are 2 scripts, that generate an iframe,
I'm trying to change the width and height of this line:
<script type='text/javascript'>
width=620,
height=382,
channel='zeyudirtc',
g='1';
</script>
This is what i'm trying:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ifr').ready(function(){
$('#ifr').contents().find('script').html('width=960, height=480, channel="zeyudirtc" ');
});
});
</script>
But this doesn't work.
Can help me please?
Thanks in advance.
If you have access to the iframes source, it is possible.
You will have to add Javascript Code to the iframe Content and the surrounding page.
The code you need inside the iframe Content should be like this:
First get the height, the iframe needs.
var height = getDocHeight();
var height = $("html").height();
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if(msie > 0){
height = Math.max(
document.documentElement["clientHeight"],
document.documentElement["scrollHeight"],
document.body["scrollHeight"]
);
}
Then you have to send a message to the surrounding page. Like this:
parent.postMessage(height, "DomainOfTheSurroundingPage");
That's it for the iframe.
On the other site you need to listen to the messages.
if (window.addEventListener) {
window.addEventListener ("message", receiveMessage, false);
} else {
if (window.attachEvent) {
window.attachEvent("onmessage", receiveMessage, false);
}
}
function receiveMessage(event)
{
var height = event.data;
do something();
}
Now you have the height (in px) to work with.
Wrap the iframe in a div.
Div
--- iframe
Then set the height of your wrapper div to 0 and the padding bottom to the height you submitted.
That should do the trick.
If you cannot add the code to the iframe Content however you can't edit the height and width of the iframe dynamically.
Check css "!important" value. In css this is a "high level"
#ifr {
height: 1000px!important;
}
http://jsfiddle.net/mraranturnik/4vqhLdpq/
OK, this is not a problem script or iframe but movi url. In url you have player size. If you want change player size you mast do somthing this
var playerUrl = $('#ifr').contents().find('iframe').attr('src');
Next write RegExp for url and put new src value for iframe in file :)
Your solution change only iframe size not a player size

Height Listener, jQuery

I'm creating a rich text editor.
Basically I have an iframe with design mode enabled. I'd like it to automatically resize when the user get near the bottom of the iframe while typing, or pasting text.
I have the function to change size.
function changeHeight() {
$(iframe).height($(iframe.contentWindow.document).height());
}
I just need to add a listener. I can't for the life of me find one that works!
Any ideas?
Much appreciated
-Will
Do this: http://sonspring.com/journal/jquery-iframe-sizing and add an onkeypress listener to check for resize.
Fair warning: if the content is not within the same domain --- it will NOT work due to XSS vulnerability prevention (you cannot trap the keypress event in this case).
This has been tested in IE7 to work, should work across most browsers. You're not actually attaching to the iFrame itself either, so much as the element you're interested in (which could very well be the body).
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#IFRAME').contents().find('textarea').bind('keypress', function() {
//Dostuff
})
});
</script>
<iframe src="/whatever.html" width="800" height="400" id="IFRAME" ></iframe>
Where you have a textarea (or div, or whatever) inside the iframe ... change the filter to your heart's content. Iframe resize code shows up in the sonspring article.
**
Edit again for code that attaches to IFRAME directly
Source [only replaced jQuery functions for native DOM. I'll clean out what I can when I have more time]:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_25589672.html
**
<script>
$(document).ready(function() {
var f = $('#IFRAME')[0];
var fwin = f.contentWindow || f.contentDocument;
fwin.document.designMode = 'on';
var evt_key = function(e) {
e = e || fwin.event;
var range = null, ret = null;
if (fwin.document.selection) {
range = fwin.document.selection.createRange();
ret = range.parentElement();
}
else if (fwin.window.getSelection) {
var range = fwin.window.getSelection().getRangeAt(0);
ret = range.commonAncestorContainer.parentNode || fwin.document;
}
fwin.parent.eventCallback();
};
if (fwin.document.attachEvent) {
fwin.document.attachEvent('onkeypress', evt_key);
}
else if (fwin.document.addEventListener) {
fwin.document.addEventListener('keypress', evt_key, false);
}
})
function eventCallback() {
alert('Key Pressed');
}
</script>
<iframe src="#" width="800" height="400" id="IFRAME" ></iframe>

Update iframe body color after load

I have a page ,page1.html that loads page2.html via an iframe . I need to change the body color of the iframe page (page2.html) to override the CSS style that's loaded on page2.html.
(both pages are on same domain). How can that be updated via Javascript ?
A bit of googling turn up this:
Scripting IFrames
It suggests window.frames[iframeName].document should work.
Since both pages lives on the same domain it should be easy.
Try this,
var changeIFrameBodyColor = function()
{
var iFrame = document.getElementById('iFrame');
var iFrameBody;
if ( iFrame.contentDocument )
{ // DOM
var iFrameBody = iFrame.contentDocument.getElementdByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
var iFrameBody = iFrame.contentWindow.document.getElementdByTagName('body')[0];
}
iFrameBody.style.color = '#ff0000';
}
Change Color
<iframe id="iFrame" src="page2.html" ../>

Categories