文档:open() 方法

Document.open() 方法打开一个文档以供 写入

这会带来一些副作用。例如:

  • 当前在文档、文档内的节点或文档的窗口上注册的所有事件监听器都会被移除。
  • 所有现有节点都会从文档中移除。

语法

js
open()

参数

无。

返回值

一个 Document 对象实例。

示例

以下简单代码会打开文档,并用多个不同的 HTML 片段替换其内容,然后再关闭它。

js
document.open();
document.write("<p>Hello world!</p>");
document.write("<p>I am a fish</p>");
document.write("<p>The number is 42</p>");
document.close();

注意

当页面加载后调用 document.write() 时,会自动调用 document.open()

内容安全

此方法受与其它属性相同的 同源策略 限制,如果这样做会改变文档的源,则无效。

三参数 document.open()

有一个鲜为人知且很少使用的三参数版本的 document.open(),它是 Window.open() 的别名(请参阅其页面获取完整详细信息)。

例如,此调用会在新窗口中打开 github.com,并将其 opener 设置为 null

js
document.open("https://www.github.com", "", "noopener=true");

二参数 document.open()

浏览器过去支持一个二参数的 document.open(),其签名如下:

js
document.open(type, replace);

其中 type 指定了你正在写入的数据的 MIME 类型(例如 text/html),如果设置了 replace(即字符串 "replace"),则指定新文档的历史记录条目将替换当前正在写入的文档的历史记录条目。

此形式现在已过时;它不会抛出错误,而是直接转发到 document.open()(即等同于不带参数运行它)。历史记录替换行为现在始终发生。

规范

规范
HTML
# dom-document-open-dev

浏览器兼容性

另见