Get iframe content height in Google Chrome - javascript

can anyone help me to do this code works on Google Chrome?
It work's perfectly on IE.
Thanks.
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
function calcIframeSize() {
var altura = $("body", $("#frameExtraFields").contents()).height();
$("#frameExtraFields").height(altura);
}
$(document).ready(function() {
$("#frameExtraFields").ready( function() {
calcIframeSize();
});
});
</script>
</head>
<body>
<iframe src="frame.html" width="80%" height="600" id="frameExtraFields"></iframe>
</body>
</html>

Considering that your iframe loads a src on the same domain, the following should do it :
<script>
$(document).ready(function() {
$('#frameExtraFields').load(function() {
$(this).height($(this).contents().height());
});
});
</script>
<iframe src="/user/login/" width="80%" height="auto" id="frameExtraFields"></iframe>
Notice I removed the fixed height you set on the iframe element and setted it to auto instead.
See this fiddle

Solution:
I do use the below code for all browser which specifically look for chrome:
The .offsetHeight returns same value in chrome compared with .scrollHeight in rest of the browsers.
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (document.getElementById) {
newheight = isChrome
? document.getElementById(id).contentWindow.document.body.offsetHeight
: document.getElementById(id).contentWindow.document.body.scrollHeight;
}
Complete function to resize the iframe height:
function autoResize(id) //id = iframe-id
{
var newheight = 500;
var newwidth;
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (document.getElementById) {
newheight = isChrome ? document.getElementById(id).contentWindow.document.body.offsetHeight : document.getElementById(id).contentWindow.document.body.scrollHeight;
newheightVisible = newheight + 30; //Don't ask me why this, i am also wondering but it works
}
if (newheight != lastheight) {
jQuery("#" + id).css('height', newheightVisible);
lastheight = newheightVisible;
}
}

Related

Scaling embedded content to fit window ? Flash or HTML5 Video

I have a panorama video that was created with a commercial product. I would like to scale the video to fit the browser width. The code in the web inspector is:
<body leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0" onload="pageInit();">
<script type="text/javascript" src="swfobject.js"></script>
<div id="flashcontent" width="1921" height="540>
To view virtual tour properly, Flash Player 9.0.28 or later version is needed.
Please download the latest version of <a href=" http:="" www.adobe.com="" go="" getflashplayer"="" target="_blank">
<embed type="application/x-shockwave-flash" src="twviewer.swf" style="undefined" id="sotester" name="sotester" bgcolor="#FFFFFF" quality="high" allownetworking="all" allowscriptaccess="always" allowfullscreen="true" scale="noscale" wmode="direct" flashvars="lwImg=&lwBgColor=0,255,255,255&lwBarBgColor=255,255,255,255&lwBarColor=255,0,255,0&lwBarBounds=1072,270,0,0&lwlocation=0&lwShowLoadingPercent=true&lwTextColor=255,0,0,0&buildSN=7.98.151110&iniFile=config_A303_Pano.bin&progressType=1&swfFile=&percentType=0&sizeFile=&href=http://caboleisure.com/panoramas/A303_Pano_Auto/_auto/flash/Tourweaver_A303_Pano.html&lwbounds=<!-%% videobounds %%->" height="540" width="1921">
</div>
<script type="text/javascript">
var jsReady = false;
function isJsReady() {
return jsReady;
}
function pageInit() {
jsReady = true;
}
function thisMovie(movieName) {
return document.getElementById(movieName);
}
function changeSceneOnLoad() {
var search = window.location.search;
var s = search.substring(1);
var arr = s.split("&");
var json = {};
for(var i = 0; i < arr.length; i++) {
var str = arr[i];
var key = str.split("=")[0];
var value = str.split("=")[1];
json[key.toLowerCase()] = value;
}
var firstValue = json['firstscene'];
var panoid = decodeURI(firstValue);
if(panoid != "undefined") {
if(thisMovie("sotester").twAPI) {
setTimeout(function() {
thisMovie("sotester").twAPI("switchToScene", panoid);
}, 500);
} else {
setTimeout(changeSceneOnLoad, 1000);
}
}
}
// <![CDATA[
var so = new SWFObject("twviewer.swf", "sotester", "1921", "540", "9.0.0", "#FFFFFF");
so.addParam("allowNetworking", "all");
so.addParam("allowScriptAccess", "always");
so.addParam("allowFullScreen", "true");
so.addParam("scale", "noscale");
so.addParam("wmode", "direct");
//<!-%% Share Mode %%->
so.addVariable("lwImg", "");
so.addVariable("lwBgColor", "0,255,255,255");
so.addVariable("lwBarBgColor", "255,255,255,255");
so.addVariable("lwBarColor", "255,0,255,0");
so.addVariable("lwBarBounds", "1072,270,0,0");
so.addVariable("lwlocation", "0");
so.addVariable("lwShowLoadingPercent", "true");
so.addVariable("lwTextColor", "255,0,0,0");
so.addVariable("buildSN", "7.98.151110");
so.addVariable("iniFile", "config_A303_Pano.bin");
so.addVariable("progressType", "1");
so.addVariable("swfFile", "");
so.addVariable("percentType", "0");
so.addVariable("sizeFile", "");
so.addVariable("href", location.href);
so.addVariable("lwbounds", "<!-%% videobounds %%->");
so.write("flashcontent");
changeSceneOnLoad();
// ]]>
</script>
</body>
A url for the page is here: Panorama
I've tried a few suggestions, like the one described here:
Preserving aspect ratio for embedded iframes
but that doesn't work. I am actually using this page as an embedded iframe from another page, but if I can get his page to scale correctly that isn't a problem. Any suggestions would be appreciated.
Check if you've dimension properties like width, height. Set them to enlarge your screen

Straight Reload/Refresh of DIV Contents on Window Resize Using

I'm adding Amazon Affiliate banners to my website, but because the banner code isn't responsive, the larger size banners break out of my container in the smaller sizes. I've created the following code so that when the page initially loads, it will load an appropriate sized banner in the correct space. However, I would like to set it so that when the browser window is resized, the DIV containing the banner code (bannerdiv) is refreshed and the script is re-executed.
I'm a novice at this, so your patience and idiot-simple instructions will be appreciated. I'm also sure this code is written in a painfully clunky manner.
NOTE: I've updated the code per suggestions in the comments, but it's still not working. Any suggestions?
<script type='text/javascript'>
function loadBanners() {
function lrgBanner() {
amzn_assoc_ad_type = 'banner';
amzn_assoc_tracking_id = 'livcouintheci-20';
amzn_assoc_marketplace = 'amazon';
amzn_assoc_region = 'US';
amzn_assoc_placement = 'assoc_banner_placement_default';
amzn_assoc_linkid = 'AC2XN3SJ34RJMGYK';
amzn_assoc_campaigns = 'outdoorrecreation';
amzn_assoc_p = '48';
amzn_assoc_banner_type = 'category';
amzn_assoc_isresponsive = 'false';
amzn_assoc_banner_id = '1XTRE8BRWXGWQJTWPJ82';
amzn_assoc_width = '728';
amzn_assoc_height = '90';
}
function medBanner() {
amzn_assoc_ad_type = 'banner';
amzn_assoc_tracking_id = 'livcouintheci-20';
amzn_assoc_marketplace = 'amazon';
amzn_assoc_region = 'US';
amzn_assoc_placement = 'assoc_banner_placement_default';
amzn_assoc_linkid = 'OTLU2UB6UY5JMUHP';
amzn_assoc_campaigns = 'outdoorrecreation';
amzn_assoc_p = '26';
amzn_assoc_banner_type = 'category';
amzn_assoc_isresponsive = 'false';
amzn_assoc_banner_id = '0CDY3FGJ2PD68NJXFKG2';
amzn_assoc_width = '468';
amzn_assoc_height = '60';
}
function smlBanner() {
amzn_assoc_ad_type = 'banner';
amzn_assoc_tracking_id = 'livcouintheci-20';
amzn_assoc_marketplace = 'amazon';
amzn_assoc_region = 'US';
amzn_assoc_placement = 'assoc_banner_placement_default';
amzn_assoc_linkid = 'G7YQZ5D43772NXLC';
amzn_assoc_campaigns = 'outdoorrecreation';
amzn_assoc_p = '42';
amzn_assoc_banner_type = 'category';
amzn_assoc_isresponsive = 'false';
amzn_assoc_banner_id = '1VHGPZ2J9GDJGYKD5G82';
amzn_assoc_width = '234';
amzn_assoc_height = '60';
}
var winwidth = window.innerWidth;
if (winwidth >= 1200) {
lrgBanner();
} else if (winwidth < 980 && winwidth >= 920) {
lrgBanner();
} else if (winwidth >=980 && winwidth < 1200) {
medBanner();
} else if (winwidth >= 600 && winwidth < 920) {
medBanner();
} else {
smlBanner();
}
}
loadBanners();
</script>
<div id="bannerdiv">
<script id="bannerscript" src='//z-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1'></script>
</div>
<script type="text/javascript">
function amznScript() {
var banDiv = document.getElementById('bannerdiv');
var oldScript = document.getElementById('bannerscript');
var newScript = document.createElement('script')
newScript.type = 'text/javascript';
newScript.src = '//z-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1';
newScript.id = 'bannerscript'
banDiv.replaceChild(newScript,oldScript);
}
</script>
<script type="text/javascript">
function adBanner() {
loadBanners();
amznScript();
}
window.addEventListener("resize", adBanner);
</script>
Found something related to Amazon banners here:
Amazon Associates Site
I don't have experience with this particular library, but I'll share some thoughts just looking at your code:
Do the docs say the numeric variable settings need to be strings or numbers? (amzn_assoc_width, amzn_assoc_height, etc). Usually, number should be without the quotes (amzn_assoc_width = 234 instead of amzn_assoc_width = '234')
Take the lrgBanner, medBanner, and smlBanner functions OUT of the loadBanners function. You have them defined inside of it. loadBanners will work fine with them outside.
Because you're defining the variables inside of functions, they may not be getting set where the Amazon script can see them (the global space). In your browser, after the page loads, open the browser console and type in the name of any of the variables in the console and it will output whatever the variable is set to. If it outputs undefined, either you're doing something wrong in the console or the variables aren't being set in the global space. Additionally, try typing window.variableName in the console to double check.
Related to the previous bullet, try prefixing all the variable definitions in your functions with window. to explicitly set them in the global space, which is where the Amazon script is probably expecting to find them.
If you can't use responsive banners for your category, try just dynamically loading the banners using the iframe banners. Here's an example using jQuery
<head>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script language="javascript">
$(window).on('load resize', function() {
winWidth = $(window).width();
if ( winWidth >= 1200) {
$('#myBanner').attr({'src':'http://rcm-na.amazon-adsystem.com/e/cm?t=codedemo-20&o=1&p=48&l=ur1&category=home&banner=1T8X6QB60F8G26A33RG2&f=ifr&linkID=WHAOQICV37C7EWOX','width':'728','height':'90'})
} else if (winWidth >= 600 && winWidth < 1200) {
$('#myBanner').attr({'src':'http://rcm-na.amazon-adsystem.com/e/cm?t=codedemo-20&o=1&p=26&l=ur1&category=home&banner=017THAMGVS89AQ891982&f=ifr&linkID=5ORSSCSEHTUJ6JZS','width':'468','height':'60'})
} else {
$('#myBanner').attr({'src':'http://rcm-na.amazon-adsystem.com/e/cm?t=codedemo-20&o=1&p=42&l=ur1&category=home&banner=1VCFP7EH9H4CBCD6ADR2&f=ifr&linkID=IHZPNRGMTYWEIYAS','width':'234','height':'60'})
}
});
</script>
</head>
<body>
<iframe id="myBanner" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
</body>
Using a blank iframe for the initial load helps to prevent the banner from changing while the page is loading.
Hope that helps!

How to get the X & Y position of an iframe from within the Iframe?

I have an iframe on a document. Using javascript, I can get the iframe's width and height and the document's width and height. I now need to get the x,y position of the iframe on the document from within the iframe.
Code is something like:
<html>
<iframe>
var documentWidth = parent.window.innerWidth;
var documentHeight = parent.window.innerHeight;
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
var iframeX = ????
</iframe>
<html>
I've tried window.offsetTop/Left, parent.window.offsetTop/Left, window.clientTop, etc and anything else I can find but keep getting 'undefined'.
Both are on the same server so I don't think I have a cross domain issue.
Any ideas?
BTW I can't use JQuery for this. JS Only.
Here is a bit more detail:
<html>
<body>
<div>
<iframe name="iframe/123/Test">
<html>
<body>
<script src="same domain"></script>
</body>
</html>
</iframe>
</div>
</body>
</html>
The script looks like this so far:
// JavaScript Document
var documentWidth = parent.window.innerWidth;
var documentHeight = parent.window.innerHeight;
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
var iframeName = window.name;
var iframeX = window.parent.document.getElementsByName(iframeName).offsetLeft;
//Var Dumps
document.write("Document Width: "+documentWidth+"<br>");
document.write("Document Height: "+documentHeight+"<br>");
document.write("Iframe Width: "+iframeWidth+"<br>");
document.write("Iframe Height: "+iframeHeight+"<br>");
document.write("Iframe X: "+iframeX+"<br>");
I get the following results on page in the iframe:
Document Width: 1566
Document Height: 652
Iframe Width: 300
Iframe Height: 250
Iframe X: undefined
Since both files are on same server, so you dont have cross domain issue, You can try following solution:
Main Html
<html>
<body>
<iframe src='iframe.html' name='iframe_name' id='iframe_id'></iframe>
</body>
</html>
Iframe Code [iframe.html]:
<html>
<body>
<script type="text/javascript">
var documentWidth = parent.window.innerWidth;
var documentHeight = parent.window.innerHeight;
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
// Get Left Position
var iframeX = window.parent.document.getElementById('iframe_id').offsetLeft;
// Get Top Position
var iframeY = window.parent.document.getElementById('iframe_id').offsetTop;
</script>
</body>
</html>
window.parent.document.getElementsByTagName('iframe') will reference every iframe in the parent's window. From there you can find your specific iframe by looping through and checking the src attribute.
Once you have your iframe, you can get it's dimensions and locations with the properties from element.getBoundingRect().
var iframes = window.parent.document.getElementsByTagName('iframe');
var yourURL = 'test.com';
var iframe;
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].src == 'test.com') {
iframe = iframes[i];
break;
}
}
var rect = iframe.getBoundingClientRect();

How to update iframe side when some link in the iframe is clicked?

I have the following code, which resize the IFrame depending on the Size of the IFrame Content:
<html>
<head>
<title></title>
</head>
<body>
<iframe src="http://page.html"
id="iframeid" width="600" height="700" scrolling="no" onload="setIframeHeight(this.id)"></iframe>
<script>
function setIframeHeight(id) {
var ifrm = document.getElementById(id);
var doc = ifrm.contentDocument? ifrm.contentDocument:ifrm.contentWindow.document;
ifrm.style.height = "10px";
ifrm.style.height = getDocHeight(doc) + 4 +"px";
}
function getDocHeight(doc){
doc = doc || document;
var body = doc.body; html = doc.documentElement;
var height =Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
return height;
}
$('iframe').css('height', $('iframe body').height() + 'px');
</script> </body> </html>
This works fine. The IFrame size is set depending on the size of the imported site
http//:page.html
The problem is that when http//:page.html contains links. When this link is clicked, the iframe size is not updated.
Question is: How to update the iframesize when a link is clicked?
Add an event listener for loads in the iframe to fire your function:
$("iframe").on("load", function() {
setIframeHeight(id);
});
This should work as long as the iframe URL is the same domain as the parent document. If it's not you'll probably run into browser security restrictions which will cause this to fail.

How to auto shrink iframe height dynamically?

I use the following code to achieve dynamic iframe height:
In the <head>:
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
In the <body>:
<iframe name="myiframe" src="somepage.html" width="100%" frameborder="0"
scrolling="no" onload='javascript:resizeIframe(this);' />
</iframe>
This codes works fine with height increasing only. So, when the content inside the iframe increases in height, the iframe updates its height and increases with it.
The problem is with height decreasing or shrinking. When the content inside the iframe decreases, it doesn't decrease and causing big unwanted white space. This only occurs in Chrome, IE & FF works fine.
Here is my Page
I want to know how to make this code works to auto shrink iframe height when it decreases?
Screenshot one:
Screenshot two:
Update 1
I placed the following code in the <head>
<script src="jquery-1.10.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
});
The iframe code in the <body>
<iframe name="dservers" src="dual_core.html" width="100%" frameborder="0"
scrolling="no" /></iframe>
The iframe not showing in the page. It appears for one second and then disappears.
Update 2
I think The problem was the $ character before (function(){, I removed it. I'm sorry I don't have much experience with jquery. I updated the page and removed the onload="resizeFrame()" but the iframe doesn't act dynamically now.
Problem Solved
I was digging in the internet and I found a code solved the whole problem for me. I would like to share it so anyone can use it in order to get dynamic iframe height.
First, put the following code between the <head> tags:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getDocHeight(doc) {
doc = doc || document;
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
function setIframeHeight(myiframeid) {
var ifrm = document.getElementById(myiframeid);
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px";
ifrm.style.height = getDocHeight( doc ) + 5+"px";
ifrm.style.visibility = 'visible';
}
</script>
<script>(function(run){
for (i=0;i<frames.length; i++) {
var f1 = document.getElementsByTagName('myiframename')[i];
if(!f1 && window.addEventListener && !run){
document.addEventListener('DOMContentLoaded', arguments.callee, false);
return;
}
if(!f1){setTimeout(arguments.callee, 300); return;}
f2 = f1.cloneNode(false);
f1.src = 'about: blank';
f2.frameBorder = '0';
f2.allowTransparency = 'yes';
f2.scrolling = 'no';
f1.parentNode.replaceChild(f2, f1);
}
})();
</script>
Second, the Iframe code in the <body> :
<iframe id="myiframeid" name="myiframename" src="somepage.html" width="100%"
frameborder="0" scrolling="no" onload='javascript:setIframeHeight(this.id);' />
</iframe>
Third and Last, the CSS:
#myiframeid{
width: 100%;
}
Note: You should have Name and ID for the Iframe.
Compatible with all browsers (Chrome, Firefox, IE).
Have a good day!
I wrote a little library that deals with all these issues and keeps the iframed sized when the content changes or the browser window is resized.
https://github.com/davidjbradshaw/iframe-resizer
I thought about it quite a bit, and think I came up with another solution that may resolve your problem from the parent document. Rather than editing the documents in your iframe. However I can't test it due to cross origin policy. Try this out and let me know how it works.
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
Hope this does it for you.
Edit: This fix would require you to remove the onload="" function.
Edit-2: You seem to have combined the two scripts. You have this:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
}
Replace that entire script with this:
$(function(){
var iframeDoc = $('iframe[name="dservers"]').contents().get(0);
$('iframe[name="dservers"]').load(function(){
docHeight = $(iframeDoc).height();
$('iframe[name="dservers"]').height( docHeight );
});
});
And remove the onload="resizeFrame()" from the iframes tag.

Categories

Resources