JavaScript document.characterSet to Check a Page’s Encoding

Use document.characterSet to read the character encoding the browser used to decode the current document. It is a read-only string property. Reading the wording of <meta charset> is a separate check.

Read the encoding the browser used

Enter document.characterSet in the developer console to see an encoding name such as UTF-8. After changing the file or server configuration, reload the page to read the new result. DOM Standard · document.characterSet

console.log(document.characterSet); // 'UTF-8'

Check why the result differs from the declaration

In an ordinary HTML load, the browser checks for a byte order mark (BOM) at the start of the file first. In its absence, a supported encoding in the HTTP response takes priority over the meta declaration. Check both the file and the response if they disagree. HTML Standard · Encoding sniffing

const declared = document.querySelector('meta[charset]')?.getAttribute('charset') ?? null;
console.log({ declared, actual: document.characterSet });

If characters look wrong or the reported value is unexpected, check the following in order.

  1. Check the file’s actual encoding in the editor and save it as UTF-8 if needed.
  2. Check that <meta charset="utf-8"> appears near the start of <head>. The entire encoding declaration element must be within the first 1,024 bytes. HTML Standard · meta charset
  3. For a hosted page, open the Network panel, reload, and select the HTML document request. Check that the response Content-Type, such as text/html; charset=utf-8, declares the encoding used to save the file. Reload and compare the console value.

Compare both values in a standalone page

Save the code as document-character-set.html in UTF-8 and open it in a browser. Typically the actual encoding is UTF-8 and the meta value is utf-8. This case difference does not by itself indicate a mismatch.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare document encodings</title>
</head>
<body>
<p id="actual"></p>
<p id="declared"></p>
<p id="sample">Café · 한글 · 日本語</p>
<script>
const actual = document.querySelector('#actual');
const declared = document.querySelector('#declared');
const charsetMeta = document.querySelector('meta[charset]');

actual.textContent = `Encoding used by the browser: ${document.characterSet}`;
declared.textContent = `HTML meta declaration: ${charsetMeta?.getAttribute('charset') ?? "No declaration"}`;
</script>
</body>
</html>

The sample includes characters from several scripts. If the text changes only after hosting the file, compare the local file with the server response to locate the difference.