【问题标题】:Does JavaScript's document.open support the MIME type parameter?JavaScript 的 document.open 是否支持 MIME 类型参数?
【发布时间】:2017-01-07 02:01:02
【问题描述】:

一些文档建议document.open() 支持将 MIME 类型作为其第一个参数。例如:HTML DOM Open Method (Dottoro)

我还有一本古老的 JavaScript 教科书,声称您可以将 MIME 类型传递给 document.open(). 但我看到的大多数文档都不是这样:

这是早期 JavaScript 中支持的参数,后来被删除了吗?

我在 DOM 规范中没有看到它:

这只是为了我的兴趣;我没有该参数的特定用例。

【问题讨论】:

  • 我今天正在尝试这个(用 application/jsontext/plain 替换活动文档),它似乎在 Chrome 中不起作用,但我不确定我是否在做有事吗。有人可以浏览浏览器(可能是源代码)并查看此功能是否仍以某种方式可用?或者对适用的 MIME 类型有什么限制——也许它只是为了区分 HTML 和 XHTML,而忽略其他类型。在现代浏览器中寻找任何类似的信息,以获得赏金。
  • 如果支持不一致,有没有办法进行特征检测?

标签: javascript dom document


【解决方案1】:

一些上下文:document.write 和 document.open 有一些问题,因此不鼓励使用它们。见

https://developers.google.com/web/updates/2016/08/removing-document-write https://www.sitepoint.com/insert-in-place-without-documentwrite/

它是一个旧的 DOM API,过去浏览器制造商在实施 w3 规范时并没有像今天那样协调。 (这是当时的参考,现在更多的是whatwg)

因此,也许有些浏览器确实为 document.open 提供了 MIME 参数,但依赖它有时会导致错误。所以不靠谱。尽可能使用替代品。事实上,它可能有一天会被完全删除。上个 dom whatwg 规范中不存在 https://dom.spec.whatwg.org/

答案是:取决于浏览器。从提供的dottoro链接看来,Safari和Chrome似乎从未支持过它。

从技术上讲,它不是 JavaScript API,而是 DOM API。

【讨论】:

  • 您提供的这两个链接都是在使用document.write() 将上下文插入文档中间解析的上下文中,这与使用document.open() 创建新文档内容完全不同,我们在这里讨论。
  • 这些是解释弃用上下文的链接。
【解决方案2】:

Chrome 不使用type 参数。

V8Document.openMethod() 方法检查 document.open(...) 的参数是否通畅,然后调用 v8Document.open1Method()v8Document.open2Method()v8Document.open2Method() 甚至没有读取它提供的第一个 (type) 参数。 v8Document.open1Method() 确实会读取它,如果未定义,则将其设置为默认值 "text/html"。然后它将type 值传递给Document.open() 方法,但从那里它被忽略了。

火狐

Firefox 使用type 参数,但唯一接受的非默认值是"text/plain"

如果缺少参数,nsHTMLDocument::Open() 方法将 type 设置为 "text/html",然后调用另一个重载。重载将除"text/html" 之外的所有type 值转换为"text/plain",然后将该内容类型应用于文档。

检测

.contentType 属性可以告诉我们document 的类型。我们不能用它来提前进行特征检测,但我们可以用它来检查文档实际打开的类型,并相应地修改我们的输出。例如:

setTimeout(function() {
  document.open('text/plain');

  if (document.contentType == 'text/plain') {
    document.write("I'm text/plain! :-D");
  } else if (document.contentType == 'text/html') {
    document.write("I'm <code>text/html</code>. :-(");
  } else {
    document.write("I'm confused! Also: " + document.contentType);
  }

  document.close();
});

【讨论】:

    【解决方案3】:

    您可以在作为链接放置的编码 URL 中指定 mime 类型。

    buffer = ...
    var blob = new Blob([buffer], {type: 'text/plain'})
    var dataUri = window.URL.createObjectURL(blob)
    window.open(dataUri)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 2012-03-23
    • 2020-03-20
    • 2019-08-06
    • 2011-01-11
    • 2020-05-31
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多