【问题标题】:Can one set an iframe's src and manipulate its contents afterwards?可以设置 iframe 的 src 并在之后操作其内容吗?
【发布时间】:2011-07-06 23:26:45
【问题描述】:

我的目标是让父页面将 iframe 的 src 从空白更改为正确的 url(在给定点使用 iframe 中的 onload 处理程序,但这不是重点),然后操作 iframe 的内容.但是,当 DOM 加载时,javascript 似乎忽略了 iframe 中不在其 src 上的任何元素。有没有办法解决这个问题?

setTimeouts 旨在允许 DOM 和 iframe 加载。 编辑:修复了一些东西。 这是包含页面:

<html><head>
    <script type="text/javascript">
        var done = false;
        var theIframe;
        window.onload = function () {
            setTimeout('stuff()', 2000);
            clearTimeout('stuff()');
        }

        function stuff() {
            if (!done) {
                theIframe = window.myiframe;
                theIframe.src = 'http://localhost/TestStuff/redirectIframe.jsp';
                done = true;
                stuff();
            } else {
                theIframe.setMe = true;
            }
        }

      </script>
</head>
      <body>
      <iframe src="" width="500" height="500" id="myiframe" name="myiframe">

      </iframe>
      </body>

这是 iframe:

<html>
  <head>
    <script type="text/javascript">
        var setMe = false;
        window.onload = setInterval('checker()', 1000);
        function checker() {
            alert('hi');
            if (setMe) {
                window.onload = null;
                top.location = 'http://www.google.com';
                alert('foundit');
            }  else alert('a');

        }

    </script>
    </head>
  <body></body>
</html>

有什么想法吗?

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

    在这段代码中:

    theIframe.src = ...;
    stuff();
    

    您立即致电stuff(),这与您所描述的相反,因此实际上您不允许任何时间加载页面。也许你对setTimeout 的工作原理感到困惑:它只是在指定时间之后安排一次执行,它不会自动延迟对函数的所有调用。

    此外,您只能将 clearTimeoutsetTimeout 返回的先前 ID 一起使用,而不是像现在这样使用代码。

    试试这样的:

    window.onload = function() {
      loadFrame();
    }
    
    function loadFrame() {
      theIframe = ...;
      theIframe.src = ...;
      setTimeout(setSomething, 2000);
    }
    
    function setSomething() {
      theIframe.setMe = true;
    }
    

    【讨论】:

    • 是的,我想这种递归没有多大意义。尽管如此,即使在 src 更改后,theIframe.contentWindow 也是未定义的。
    • @Rujiel:这很奇怪——如果页面确实已经完成加载,就不应该发生这种情况。
    • 如果我必须先修改 src,则无法访问 iframe 的 js 中的任何内容。似乎只有 DOM 会在 iframe 刷新时更新,而 iframe 上的 js 不会被考虑在内?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2012-04-04
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多