繁体   English   中英

如何用 JavaScript 覆盖整个文档

[英]How do I overwrite an entire document with JavaScript

由于以下原因,这不是一个重复的问题:

  • 我问的是如何在没有 jQuery 或任何其他 JavaScript 花哨扩展的情况下用 JavaScript 替换整个 HTML 文档。 与此问题类似的其他一些问题涉及 AJAX 或 jQuery 等特定事物。
  • 我不是在问为什么document.write()只附加到页面。 也许我正在寻找的纯 JavaScript 解决方案可能包含该功能,但不能仅是因为它本身是不够的。

我想要做的是覆盖一个网页,因为它只用 HTML 显示在浏览器中。 函数document.write()仅将传递给它的任何参数附加到文档正文中。 属性document.documentElement.outerHTML可以被读取,但与在页面的子元素上使用不同的是,它不能被写入,即使可以,它也会保持 DOCTYPE 不变。

我正在处理一个书签,所以这个 JavaScript 不会在页面中运行,这意味着脚本在运行时被覆盖没有问题。 它也可以在浏览器的开发人员工具中运行。

例如,假设我在浏览器中打开了about:blank DOM 的内容如下所示:

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

我希望能够用我想要的任何字符串覆盖它。 所以,例如,我可以让它看起来像这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Example</title>
    </head>
    <body>
        <p>This is an example.</p>
    </body>
 </html>

我怎样才能实现那种对文档的覆盖?

您可以使用document.implementation.createDocumentType重写 doctype 和document.getElementsByTagName以获取 DOM 元素,然后使用innerHTMLsetAttribute重写。

 var newDoctype = document.implementation.createDocumentType('html','-//W3C//DTD XHTML 1.0 Transitional//EN','http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdd'); document.doctype.parentNode.replaceChild(newDoctype,document.doctype); document.getElementsByTagName('html')[0].setAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); var doc = document.getElementsByTagName('html')[0]; doc.getElementsByTagName('head')[0].innerHTML = '<title>Example</title>'; doc.getElementsByTagName('body')[0].innerHTML = '<p>This is an example.</p>';
 <!DOCTYPE html> <html> <head> </head> <body> </body> </html>

编辑:

更新以包含 Xweque 和 xmlns 属性的注释。

document.write('Some Text')

document.write重写页面的代码。

尝试这个:

function one() {
  document.write('<html><body><pre>the first html</pre></body></html>');
  document.close();    // this makes the difference
}
function two() {
  document.write('<html><body><pre>the second html</pre></body></html>');
  document.close();
}

请参阅linstantnoodles在问题document.write() overwriting the document?的回答document.write() overwriting the document? ,该document.open被隐式调用之前document.write叫,但document.close不和
当文档关闭时document.write() = 重写文档;
当文档打开时document.write() = 附加到文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM