我使用HTML属性标题设置如下提示:
<a href... title="Go to next chapter">Go</a>
然后jquery插件将遍历所有的[title]属性,并生成漂亮的工具提示。非常简单,为上面的链接创建了一个新的DIV
<div style="position:absolute...">Go to next chapter</div>
问题是,标题是用户可编辑的,所以他可以写任何他想写的东西。我第一次认为HTML编码很好,但结果发现我错了。
如果我有
<a id="a" title="<script>alert(10);</script>">Go</a>
然后tooltip div如下所示:
<div style="position:absolute..."><script>alert(10)</script></div>
1)为什么浏览器在查询其值时会解码标题属性?
2)如何解决?(我知道有一个解决方案是双重HTML编码,但它太满了)
如何测试它:考虑这个代码
<html>
<body>
<!-- encoding once, this doesn't work -->
<a id="a" title="<script>alert(10);</script>">atitle</a>
<!-- encoding twice, this works -->
<a id="b" title="&lt;script&gt;alert(10);&lt;/script&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>