javascripthtmldjangounicodezero-width-space

Zero-width space makes HTML link unclickable


I'm creating a link to a page based on the name the user gave that page. However, the link is unclickable if the name is a zero-width space.

How can I stop users from giving pages unclickable names? I'd like to allow Unicode characters if possible.

The names are being entered into the database through a Django form, and the HTML link is being built in jQuery. Django complains if the name is a regular space, but accepts a zero-width space.

var linkText1 = 'foo', linkText2 = '\u200b';
$('#ex1')
  .append($('<a>')
  .text(linkText1)
  .attr('href', 'javascript:alert("clicked.")'));
$('#ex2')
  .append($('<a>')
  .text(linkText2)
  .attr('href', 'javascript:alert("clicked.")'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="ex1">Example 1 </p>
<p id="ex2">Example 2 </p>


Solution

  • Inspired by Nawed's answer and devdob's comments, I decided to add a suffix when the link text didn't contain any letters or numbers. That will avoid corrupting any useful Unicode text, but it should always provide a usable link.

    Unfortunately, it's not smart about Unicode. Chinese words, for example, will always get the link suffix.

    Some options for improvement:

    1. Find a list of all the invisible Unicode characters and look for them explicitly. I'm worried that new invisible Unicode characters could be added in the future.
    2. List more blocks of visible Unicode characters beyond Latin letters and numbers. This seems like the best option, but I think my application will be fine as long as it doesn't Unicode names.

    function addLink($p, linkText) {
      if ( ! /\w/u.test(linkText)) {
        linkText += ' [link]';
      }
      $p.append($('<a>')
        .text(linkText)
        .attr('href', 'javascript:alert("clicked.")'));
    }
    var linkText1 = 'foo', linkText2 = '\u200b', linkText3 = '网站';
    addLink($('#ex1'), linkText1);
    addLink($('#ex2'), linkText2);
    addLink($('#ex3'), linkText3);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id="ex1">Example 1 </p>
    <p id="ex2">Example 2 </p>
    <p id="ex3">Example 3 </p>