2009-06-13

Firefox の a.href と a.getAttribute('href') の違い

こんばんは。なかじまんです。Firefox で注意しましょうという小ネタです。

次のソースコードは Firefox3 と Firefox2、その他のブラウザで href 属性を参照した結果が異なります。

<script type="text/javascript">
jQuery(function($) {
console.log($('#a')[0].href);
console.log($('#a')[0].getAttribute('href'));
console.log($('#a').attr('href'));
});
</script>
<a id="a" href="http://example.com/?foo's bar">foo' bar</a>

Firefox3

foo%27s%20bar
foo's bar
foo's bar

Firefox2

foo's%20bar
foo's bar
foo's bar

その他

foo's bar
foo's bar
foo's bar

この事象って多くの人が知っていることでしょうか。JavaScript ライブラリを使わないでコードを書いていてはじめて気がつきました。

bugzilla を検索してみると、次の report がありました。

Bug 405890 – When getting a DOM element's href property, and when the href contains a space, the space is URLencoded as %20
My first search didn't find a bug that this is a direct duplicate of, but in spirit it's a duplicate of all the bugs talking about things like being surprised to get back an absolute URI when the href attribute had a relative URI - the DOM spec says .href is a URI, not the string you put in, and if you want the string you put in, you should .getAttribute("href") instead.
DOM 仕様の解釈の曖昧さから生じているのでしょうかね。間違ってはいないと思いますが、期待どおりではない感じですね。

なので href 属性を参照するときは、クロスブラウザをサポートする JavaScript ライブラリか getAttribute メソッドを使いましょということです。ご参考まで。

0 件のコメント: