- 2010-02-03 (水) 1:00
- Programming
自分のドメイン内はページ内リンク、自分のドメイン外は"target=_blank"で別ウィンドウで表示したい場合。
<script type="text/javascript">
<!--
var p = location.protocol;
var h = location.hostname;
window.onload = function () {
var nodes = document.getElementsByTagName('a');
var i = nodes.length;
while (--i >= 0){
var l = nodes[i].getAttribute('href');
if ( (l.indexOf(p) == 0) && (l.indexOf(h) < 0) )
nodes[i].setAttribute('target', '_blank');
}
}
// -->
</script>
JavaScript はあまり書きなれていないのだけど、こんな感じでいいのだろうか。とりあえず動いてるっぽ。でも、これだと厳密には http://exsample.com/my-domain/ だと別ウィンドウで表示されないよな。
l.indexOf(h) < p.length + ‘//’.length + h.length
だったら完璧かな。そこまでする気はないけれど。location.host を使えばいいのかな?
ってか、 foreach ないの? JavaScript って。知らんかった。
<script type="text/javascript">
<!--
var p = location.protocol;
var h = p + '//' + location.host;
window.onload = function () {
var nodes = document.getElementsByTagName('a');
var i = nodes.length;
while (--i >= 0){
var l = nodes[i].getAttribute('href');
if (l.indexOf(p) == 0 && l.indexOf(h) != 0)
nodes[i].setAttribute('target', '_blank');
}
}
// -->
</script>
こっちの方がいいや。
- Newer: 1月の反省
- Older: Settings Extension のインストールでコケる → 解決。

