我使用 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>
然后工具提示 div 看起来像这样:
<div style="position:absolute..."><script>alert(10)</script></div>
1)为什么浏览器在查询title属性的值时会解码它的值?
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>