gpt4 book ai didi

javascript - 新创建的 DOM 文档位置

转载 作者:行者123 更新时间:2023-11-30 13:59:40 24 4
gpt4 key购买 nike

我使用
创建了一个新的DOM文档 var foo=document.implementation.createDocument(null, "html");
我想设置一些属性,包括位置。但是 foo.location 返回 null 并且 foo.location.href="https://stackoverflow.com" 返回错误 无法设置属性“href”为 null。如何设置位置?

最佳答案

您必须先建立一个browsing context对于@rlemon 建议的那个文件。

提供浏览上下文的最简单方法是将新文档放入 iframe 元素,方法是将 iframe 的文档替换为您的新文档。

这个例子是从关于如何做到这一点的 MDN 演示中提取的:

    var frame = document.getElementById("theFrame");
// note the use of createHTMLDocument
var doc = document.implementation.createHTMLDocument("New Document");
var destDocument = frame.contentDocument;
var srcNode = doc.documentElement;
var newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
// Now it is in a browsing context and the location can be set
destDocument.location.href = "//example.com";

我注意到您正在创建一个 HTML 文档。因此,我使用了 createHTMLDocument 而不是 createDocument(它创建了一个 XMLDocument)。

由于 iframe 被阻止,此示例不会在此处作为代码段运行。所以这是一个jsbin with this code running .

关于javascript - 新创建的 DOM 文档位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com