src iframe的动态高度和宽度

I've configured some third party website in my application as iframe src. Now I want to makes its width and height based on the contents of the src in iframe. I refereed this.

但是函数getDocHeight返回零。

I have refereed answer from this link. But when I try to execute it, the object this.contentWindow.document it throws CORS issue. What else can I do?

这是我尝试过的:

function getDocHeight(doc) {
    doc = doc || document;
    // stackoverflow.com/questions/1145850/
    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(id) {
    var ifrm = document.getElementById(id);
    var doc = ifrm.contentDocument? ifrm.contentDocument: 
        ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    // IE opt. for bing/msn needs a bit added or scrollbar appears
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.style.visibility = 'visible';
}

<iframe
    id="ifrm"
    ref="iframe"
    src={url}
    width="100%"
    scrolling="no"
    frameBorder="0"
    onLoad={this.setIframeHeight("ifrm")}
/>
评论