Chrome 对比 Firefox Javascript 行为

Chrome vs Firefox Javascript behavior

这是 "data:" URI,在浏览器中加载它。

data:text/html,<script>alert("#")</script>

我在 Chrome 中执行了 alert(),但在 Firefox 中没有。 Firefox 删除“#”字符和所有后续字符。 我怎样才能让 FF 发出 alert("#")?

更新:我理解“#”片段部分,但问题更像是"Why did Chrome ignore the "片段“的情况,并认为它是一个普通字符,而FF却没有?”。

一个#在一个URL中有特殊的意义(表示片段部分的开始)。您必须将其编码为 %23 才能将其作为数据包含在内。

必须对数据 URI 的数据部分进行编码,# 不允许作为文字字符。来自 Wikipedia page

The data, separated from the preceding part by a comma (,). The data is a sequence of octets represented as characters. Permitted characters within a data URI are the ASCII characters for the lowercase and uppercase letters of the modern English alphabet, and the Arabic numerals. Octets represented by any other character must be percent-encoded, as in %26 for an ampersand (&).

...引用 RFC3986.

所以你的数据 URI 应该是:

data:text/html,%3Cscript%3Ealert(%22%23%22)%3C%2Fscript%3E

...在 Chrome 和 Firefox 中都有效:

<a href="data:text/html,%3Cscript%3Ealert(%22%23%22)%3C%2Fscript%3E">Click here</a>

您可以使用 JavaScript 的 encodeURIComponent 获取 URI 数据,例如:

var dataUri = "data:text/html," + encodeURIComponent('<script>alert("#")</script>');