【问题标题】:Copying an entire document into an iframe with javascript使用 javascript 将整个文档复制到 iframe
【发布时间】:2008-12-18 18:09:56
【问题描述】:

这听起来很奇怪,但这是我试图用 javascript 做的事情(这都是由事件处理程序触发的):

  1. 将页面的内容(最好是整个文档或至少 documentElement 对象)保存到变量中。
  2. 创建一个 iframe 并将其插入 身体。
  3. 将 iframe 的文档替换为保存的文档(这样 iframe 现在与外页的内容相同)。
  4. 更改外页。

除了替换 iframe 文档的部分外,一切都很花哨。我尝试了很多不同的方法,但都有问题(如下所述)。当页面在 iframe 中时,我需要事件处理程序、样式、链接等才能正常工作。

是的,我意识到我可以将 iframe 的 src 设置为当前页面的 url,但我宁愿页面不必加载。如果我不能想出一个解决方案,这就是我要做的。


我已经尝试过的事情:

var html = iframe.contentWindow.document.importNode(document.documentElement, true);
iframe.contentWindow.documentElement = html;

我收到一条错误消息(“设置只有 getter 的属性”)。

var html = iframe.contentWindow.document.importNode(document.documentElement, true);
var idoc = iframe.contentWindow.document;
while(idoc.firstChild) idoc.removeChild(idoc.firstChild);  // remove all children (firefox automatically creates an html element for iframes with no src)
idoc.appendChild(html); // insert a new documentElement

这似乎可行,但不会重新渲染样式,并且事件处理程序也不起作用。有趣的是,链接也不起作用,它们甚至没有使用浏览器的默认样式。也许这是因为 DOCTYPE 没有复制到 iframe 中?

iframe.contentWindow.document.documentElement.innerHTML = document.documentElement.innerHTML;

这与 removeChild/appendChild 方法的行为相同。


似乎如果我可以让浏览器重新呈现样式并重新注册事件处理程序,那么我会很高兴,但我不确定这是否可能。

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

    关于最后一种方法,可能你要复制的窗口的DOM还没有加载?

    至于 Doctype,您可以从头开始重建它并使用 document.write 将其插入到 html 节点之前。

    doctype 可以通过 document.doctype 访问,但这只有一个 getter。

    【讨论】:

    • 我在 Prototype 的“dom:loaded”事件触发时创建 iframe,并在“click”事件中复制文档。不过,我会试试 doctype 的东西,看看它是否有效。
    • 我正在尝试输入 doctype,但在使用 document.write 和 document.appendChild 时遇到问题。我已经尝试将 document.close() 放在所有地方,但似乎没有任何效果。
    • 在我的脑海中,不会使用 appendChild 添加 doctype,因为 DocType 本身是注释而不是节点,但我可能错了。我会在另一个框架的文档类型的字符串中构建 document.type。然后我会使用 document.write 以..的形式复制。
    • document.write(docTypevariable+""+ ..documentElement.innerHTML+"
    【解决方案2】:

    如果您在 iframe 中加载一个空的 html 样板文档会怎么样? 在某个文件夹“myFolder/sparePage.html”中创建一个文档,然后执行

    var myIframe = document.createElement("iframe");
    myIframe.style.display = "none";
    document.body.appendChild(myIframe);
    function myIframeLdd(){
       console.log("myIframe is loaded");
        //....your iframe ready code here
       myIframe.removeEventListender("load",myIframeLdd,false);
    }
    myIframe.addEventListener("load", myIframeLdd, false);
    myIframe.src = "myFolder/sparePage.html"

    【讨论】:

      猜你喜欢
      • 2016-06-14
      • 1970-01-01
      • 2020-03-20
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多