简体   繁体   中英

Determine the width of an iframe's parent container inside the iframe on mobile pbrowsers

Our customers host their own HTML web pages, and we provide some of the content of those pages as embedded iframe elements. (Which means their content and our content have different domain origins.) They typically provide a div element that contains our iframe element. (Note that we have no control over their web page content, only over our iframe content.)

The iframe contains JavaScript code that determines the maximum size it can fill, which should be the dimensions of the outer div . This maximum width is used to control (show/hide) scrolling elements within the iframe content.

The problem is that on some mobile browsers , the contents of the iframe is not properly constrained (clipped) to the size/boundaries of its parent <div> . In other words, the dimensions of the iframe are larger (wider) than its parent div . (This is not a problem on desktop browsers.)

So the question is : How can the iframe code determine the true proper size of its parent element (especially cross-domain)? The best I can get, it seems, is the apparent size of the iframe itself and its children elements.

Adding overflow:hidden to the parent div properly hides/clips the iframe content that extends past the div bounds, but the iframe code still cannot determine what that dimension (width) actually is. (Again, this is apparently not a problem on desktop browsers.)

Note: Similar questions (eg, Detect the width of an iframe from within the iframe ) address the problem of accessing the dimensions of the iframe itself from within the iframe ; I need to access the dimensions of the iframe 's parent container.

SOLUTION

I ended up placing the iframe element within its own div element, and accessing the width of that containing element. (There does not appear to be any way for the iframe to directly access its parent.)

Your iframe page has to talk the other pages. Here is the my example repo on Github, this is what I'am talking...

EDİT:

Every outsource page:

function windowWidth(){
    return document.getElementById('content').clientWidth;
}

Iframe page:

window.onload = function(){

    setInterval(function(){

      var iframeWidth = document.getElementById('iframe').contentWindow.windowWidth();
      document.getElementById('iframe').style.width = iframeWidth + "px";

     }, 10);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM