javascript - iframe onload 在 iframe 未准备好时触发

标签 javascript reactjs iframe

所以我在 vanilla React 中遇到了问题。 我在 ready() 函数中有这行代码:

var current = this;    
React.createElement(
            "iframe",
            {id: "iframeController", 
             ref: "iframe", 
             src: "data:text/html;charset=utf-8," + escape(notification.description), 
             onLoad: current.iframeLoaded(this)}
)

notification.description 来 self 对 this.state.notifications 中的对象所做的映射

以及跟随它的这个函数

iframeLoaded(iframe) {
    if(iframe) {
        iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";         
    }
}

但是,如果我 console.log iframeLoaded 中的 (iframe) 元素,它将返回 null。如果我 getElementById 也是如此,只不过它是未定义的。

我做了一个 setTimeout 来查看是否是组件更新问题,事实证明确实如此。因此,即使在 Chrome 中,onLoad 也会在 src 有时间渲染之前触发。

我正在尝试获取高度,以便可以在窗口中设置它,允许它调整大小并获取我得到的 iframe 的完整高度。

任何人都可以给我一些关于如何解决这个问题的建议吗?

最佳答案

我怀疑问题出在这一行:onLoad: current.iframeLoaded(this)}。在这种情况下,onLoad 被设置为 current.iframeLoaded(this) 的返回值。

我相信您想将值包装在函数中(不是箭头表示法,而是传统函数):

onLoad: function(){current.iframeLoaded(this);}}

关于javascript - iframe onload 在 iframe 未准备好时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52765556/

相关文章:

javascript - 在 Shopify 中通过 Javascript 将产品价格增加 20%

javascript - CRA 环境变量中的 npmject 收到 undefined 后

javascript - knockout/JavaScript 忽略多重点击

JavaScript 小书签和 URL 编码

javascript - 在react js中传递和显示对象数组

javascript - 在 create-react-app 项目中放置 webpack.config.js 的位置

javascript - 在后台上下文中的脚本之间进行通信(后台脚本,浏览器操作,页面操作,选项页面等)

dom - 将 javascript 函数注入(inject) Iframe

javascript - 到达 html 页面的末尾等于 "page loaded"吗?

javascript - 单击第二个下拉黑框时应保持可见