views:

225

answers:

1

I use html attribute title to set some hints like this:

 <a href... title="Go to next chapter">Go</a>

Then the jquery plugin goes through all the [title] attributes and makes pretty tooltips. Very simplified a new div is created for the link above

<div style="position:absolute...">Go to next chapter</div>

The problem is, that the title is editable by user, so he can write whatever he wants. I first thought that html encoding is fine, but it turned out that I was wrong. If I have

<a id="a" title="&lt;script&gt;alert(10);&lt;/script&gt">Go</a>

then the tooltip div looks like this:

<div style="position:absolute..."><script>alert(10)</script></div>

1) Why browser decodes the title attribute when querying its value?

2) And how can I solve it? (I know that one solution is double html encoding, but it's awfull)

How to test it: consider this code

<html>  
 <body>  
  <!-- encoding once, this doesn't work -->
  <a id="a" title="&lt;script&gt;alert(10);&lt;/script&gt">atitle</a>  
  <!-- encoding twice, this works -->
  <a id="b" title="&amp;lt;script&amp;gt;alert(10);&amp;lt;/script&amp;gt">btitle</a>  

  <script>  
   function w(x){ document.write(x.attributes["title"].value);}  
   w(a);  // shows alert
   w(b);  // outputs it correctly into the page
  </script>  
 </body>  
</html>
+1  A: 

1) The attribute value is the decoded value - it's the only way that makes sense if you think about it. If you set a javascript value to "\n" then alert it, do you want to get back "\n" or a real newline? The title attribute is text... you just happen to have to HTML-encode it to write it.

2) You could double-encode it, or you could use a text node:

var node = document.createTextNode(x.attributes['title'].value);
document.appendChild(node);

This is the preferred way, then spiders / non-javascript browsers will see the correct title attribute.

Greg