Detect <iframe> height and width from inside the iframe

▼魔方 西西 提交于 2019-12-18 12:26:06

问题


I doubt this is actually possible but Im prepared to be corrected.

What I need is to be able to detect the width and height of an iframe from within the iframe, so if the iframe src is iframeContent.html I need to be able to surface the values on this page.

I have no control over the page that hosts the iframe only the contents of the iframe.

Is this possible?


回答1:


You can always get the web page dimensions, no matter if the page is loaded inside an iframe or a new window it always works the same way. This is a function I've found used to get window dimensions, you can also use it to get an <iframe> dimensions.

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  window.alert( 'Width = ' + myWidth );
  window.alert( 'Height = ' + myHeight );
}
  • source (thanks Andy E for adding the link)
  • jsFiddle example


来源:https://stackoverflow.com/questions/7808729/detect-iframe-height-and-width-from-inside-the-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!