html - 浏览器如何确定使用的编码?

标签 html encoding

我知道有两种设置编码的方法:

  1. 使用 Content-Type header 。
  2. 通过在 HTML 中使用元标记

由于 Content-Type header 不是强制性的并且需要显式设置(服务器端可以根据需要设置它)并且元标记也是可选的。

如果这两者都不存在,浏览器如何确定用于解析内容的编码?

最佳答案

他们可以根据启发式猜测

我不知道现在的浏览器在编码检测方面有多好,但 MS Word 在这方面做得非常好,甚至可以识别我以前从未听说过的字符集。您可以打开一个随机编码的 *.txt 文件并查看。

This algorithm usually involves statistical analysis of byte patterns, like frequency distribution of trigraphs of various languages encoded in each code page that will be detected; such statistical analysis can also be used to perform language detection.

https://en.wikipedia.org/wiki/Charset_detection

Firefox 使用 Mozilla Charset Detectors .解释了它的工作方式 here你也可以change its heuristic preferences . Mozilla 字符集检测器甚至是 forkeduchardet哪个效果更好并检测到更多语言

[更新:如下评论,它移至chardetng自 Firefox 73]

以前使用的 Chrome ICU detector但切换到CED几乎2 years ago


没有一个检测算法是完美的,他们可以猜错 like this ,因为它只是在猜测!

This process is not foolproof because it depends on statistical data.

所以这就是著名的 Bush hid the facts错误发生。错误的猜测也会给系统带来漏洞

For all those skeptics out there, there is a very good reason why the character encoding should be explicitly stated. When the browser isn't told what the character encoding of a text is, it has to guess: and sometimes the guess is wrong. Hackers can manipulate this guess in order to slip XSS past filters and then fool the browser into executing it as active code. A great example of this is the Google UTF-7 exploit.

http://htmlpurifier.org/docs/enduser-utf8.html#fixcharset-none

因此,编码应始终明确说明。

关于html - 浏览器如何确定使用的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43148464/

相关文章:

javascript - 克隆后无法从选择框中选择选项

authentication - 在数据源中使用认证别名有什么好处?

python - 传递给其他命令时编码发生变化?

python - 如何使用字符编码在文件中存储随机字节?

java - Java 中的 Drupal 风格 base64 编码

html - 柔性 : how to right align an item which centers on wrap

javascript - 如何在 HTML 的 head 元素内有条件地呈现 CSS 和 JavaScript

python urllib2 utf-8编码

javascript - 动态复选框列表不显示数据

html - 为什么我的 anchor 标签扩展了 800 像素?