简体   繁体   中英

How to get an iframe contents width?

I got an iframe in my page. Like this :

<iframe width="600px">
    <html>
        <head>
        </head>
        <body>
            <p>Some text</p>
            <img src="/foo/bar/test.png" />
        </body>
    </html>
</iframe>

I want to be able to detect if the iframe contents is larger than 600px. I tried this one :

var iframe = $('iframe');
if (iframe.width() < iframe.contents().width()) {
    console.log('contents larger than the iframe');
}

It works on Firefox and Internet Explorer. But not on Chrome. On Chrome, iframe.contents().width() is 600.

I tried iframe.contents().find('body').width() but the result is also 600.

How can i detect the iframe contents real width in Chrome ?

Try adding width checking after loading iframe, like suggested here

it did the trick for me.

I guess you want to get the iframe width of a tinymce iframe. You could give this code snippet a try. What still needs to be done is to set the caret to the outer right position. The idea is to measure the caret location.

var ed = tinymce.editors[0]; // or tinymce.get('your_editor_id')
var rng = ed.selection.getRng();
rng.collapse(true);

var bm = ed.selection.getBookmark();
var $marker = $(ed.getBody()).find('#'+bm.id);
var elem = ed.getDoc().getElementById(bm.id+'_start');

try {
    box = elem.getBoundingClientRect();
} 
    catch(e) 
{
    console.log('adjustIframePosition (irbasics) error creating box: ' + e);
}


var doc = ed.getDoc(),
    docElem = doc.documentElement,
    body = ed.getBody(),
    win = ed.getWin(),
    clientTop  = docElem.clientTop  || body.clientTop  || 0,
    clientLeft = docElem.clientLeft || body.clientLeft || 0,
    scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
    scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
    top  = box.top  + scrollTop  - clientTop,
    left = box.left + scrollLeft - clientLeft;

console.log('iframe width: ' + (box.left + scrollLeft) );

I don't use jQuery, but maybe can help this:

var iframe = document.getElementById("myiframe");
var doc = iframe.contentDocument || iframe.contentWindow.document;

alert(doc.body.scrollWidth); // use this property for check

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