【问题标题】:React - Accessing inline created iframe elementsReact - 访问内联创建的 iframe 元素
【发布时间】:2020-08-15 22:57:04
【问题描述】:

我有一个 iframe,我正在尝试访问它的 textarea 并添加一个侦听器:

    onIframeRef = (node) => {
       this.Iframe = node;
    };

  componentDidMount() {
      let iframeDoc = this.Iframe.contentDocument || this.Iframe.contentWindow.document;
      let textArea = iframeDoc.contentWindow.document.getElementById("some-textarea")[0];
      textArea.addEventListener("input", this.onInput);
   }

    render() {
            return <div>
                 <iframe
                  ref={this.onIframeRef}
                  sandbox="allow-same-origin"
                  srcdoc='<html><body><textarea id="some-textarea"></textarea></body></html>'
                  ></iframe>
             </div> 
    }

我很困惑设置 srcdoc 是否意味着代码是相同的来源,因为代码不起作用,this.Iframe 既没有 contentDocument 也没有 contentWindow

【问题讨论】:

    标签: javascript html reactjs iframe same-origin-policy


    【解决方案1】:

    srcdoc 表示它的来源相同,但是您的代码由于以下两个原因无法正常工作:

    1. 确实,当componentDidMount运行时,意味着iframe已经插入到dom中,但这并不意味着iframe本身已经被加载,所以下面的代码执行时会返回null
    iframeDoc.contentWindow.document.getElementById("some-textarea")
    
    1. let textArea = iframeDoc.contentWindow.document.getElementById("some-textarea")[0]
      

    通过 id 获取元素返回元素本身,因此 [0] 将返回 undefined。

    要使您的代码正常工作,您应该在 iframe 上侦听 load 事件,然后在该事件侦听器中运行您的代码(以确保 iframe dom 本身已被加载)

    这是一个正在运行的代码框https://codesandbox.io/s/funny-turing-25wn9?file=/src/App.js

    【讨论】:

    • 谢谢,解释了很多! (第二种是复制代码时发生的情况)
    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2010-09-12
    • 1970-01-01
    • 2013-03-22
    • 2015-03-12
    相关资源
    最近更新 更多