简体   繁体   中英

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 = '\​'; $('#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> 

Detect and replace the zero-witdh space with null or empty space. Then when creating your link either skip that text (show no link if null) or show a default link text like "Click Here".

Here is some code to detect zero-width space and replace it with empty string:

linkText2 = linkText2.replace(/\u200B/g,'');

Here we set a default if given is empty:

linkText2 = (linkText2 == '') ? "Click Here" : linkText2;

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 = '\​', 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM