【问题标题】:Dynamically create an iframe and attach onload event to it动态创建 iframe 并将 onload 事件附加到它
【发布时间】:2011-05-31 06:24:23
【问题描述】:

我已经动态创建了一个 iframe 并为其添加了 src 属性。然后我将此 iframe 附加到页面的正文中。知道我想将onload 事件附加到 iframe 以读取 iframe 内容。有人可以建议我该怎么做吗?

frame = document.createElement('iframe');
frame.setAttribute('src','http://example.com');
body.appendChild(frame);
frame.onload = function(){
    alert('hi'); // here I want to read the content in the frame.
}

【问题讨论】:

    标签: javascript iframe dom-events


    【解决方案1】:

    有些浏览器确实有 iframe 的 onload 事件,首先你应该在设置 iframe 的 src 属性之前尝试附加它。

    我会完全避免使用它,因为在某些浏览器中它可能不会在某些条件下触发(例如,目标在 IE 的缓存中)。

    您可以使用计时器来检查框架的 contentWindow 的就绪状态是否已完成

    var inter = window.setInterval(function() {
        if (frame.contentWindow.document.readyState === "complete") {
          window.clearInterval(inter);
          // grab the content of the iframe here
        }
    }, 100);
    

    【讨论】:

    • 它对我不起作用,因为 iframe 位于另一个来源,我收到 SecurityError: Blocked a frame with origin "localhost" 无法访问跨域框架。
    • 你是对的,它确实只适用于同源帧。假设 window.onload 功能今天更好,这可能更安全,具体取决于您计划支持的浏览器。
    【解决方案2】:

    您可以将load event 侦听器添加到 iframe 的 contentWindow,就像任何其他 Window 一样。

    这是example

          iframe = document.createElement('iframe')
          iframe.setAttribute('src', 'https://example.com/')
    
          document.getElementsByTagName('body')[0].appendChild(iframe)
          const onLoaded = function() {
            console.log('iframe loaded');
          }
          if (iframe.contentWindow.document.readyState === 'complete') {
            console.log('already loaded')
            onLoaded()
          } else {
            iframe.contentWindow.addEventListener('load', onLoaded)
          }
    

    【讨论】:

      【解决方案3】:

      我刚试过这个,它在 Chrome 中工作:

      var iframe = document.createElement('iframe');
      // append iframe to DOM however you like then:
      iframe.contentWindow.parent.location.href // properly gives parent window's href.
      

      W3school 表示所有主流浏览器都支持contentWindow

      【讨论】:

      • 我相信(W3school)他们,数以千计的人
      【解决方案4】:

      我怀疑您是否可以将 onload 事件附加到 iframe。它不适用于所有浏览器。另一方面,您可以检查 iframe 是否由以下方式加载:

      window.onload=function()
      {
      var iframe=document.getElementById('myframe');
      if(iframe) 
          alert('The iframe has just been loaded.');
      }
      

      或者使用 AJAX 将内容加载到您的容器中。使用 AJAX,您可以设置适当的加载完成事件。

      【讨论】:

      • 尝试 onload="return function_name();"
      • 如果你想自己处理事情并稍微复杂一点,你可以制作一个定期计时器,它会记住 iframe 的 document.body.innerHTML 并在每次更改时触发你自己的事件.如果只需要一次,可以在定时器触发事件​​后销毁它。
      • 添加 iframe.onload 监听器来检查加载
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 2018-12-05
      • 2012-08-01
      • 1970-01-01
      相关资源
      最近更新 更多