1

According to this question, many characters (#, <, >, [, ], {, }, ...) should be forbidden in URL fragments (that is, the part of an URL after the #). But a test script I wrote seems to indicate that most current browsers allow some of these characters:

const unsupported = [];
for (let charCode = 32; charCode < 127; charCode++) {
  const c = String.fromCharCode(charCode);
  window.location = `#${c}`;
  const afterRoundtrip = window.location.href.match(/#(.*)/)[1];
  const characterIsSupported = afterRoundtrip === c;
  if (!characterIsSupported) {
    unsupported.push(c);
  }
}
console.log('Unsupported: ', unsupported);

This script iterates over all printable ASCII characters, tries to append each to the URL after a hash, reads it back, and outputs the characters that the browser didn't allow.

On Chrome, the output was [" ", """, "<", ">", "`"]; on both Safari and Edge, it was [" "]. So it seems that almost all ASCII characters are allowed within URL fragments.

I'm confused: Should browsers allow all these special characters in URL fragments? If so, can I rely on this behavior and use these characters for single-page applications? Is there some standard I'm not aware of?

Daniel Wolf
  • 12,855
  • 13
  • 54
  • 80
  • _"Should browsers allow all these special characters in URL fragments?"_ Maybe. Browsers are very forgiving in many ways, but whether they should do what you're noticing is debatable. _"If so, can I rely on this behavior and use these characters for single-page applications?"_ Probably not – j08691 Jun 28 '19 at 16:01
  • I can (and do) write horribly malformed HTML & browsers will happily render it as I expect, they make allowances for all kinds of things. – Alex K. Jun 28 '19 at 16:02
  • Firefox disallows a lot more. – Pointy Jun 28 '19 at 16:03
  • It isn't really the job of the browser to decide whether any URL is valid or not - that is the job of the web server, so I would _expect_ the browser to be lenient, but certainly not rely on anything that is contrary to the spec. – MikeB Jun 28 '19 at 16:05

0 Answers0