Home > Programming > [JavaScript] ドメイン外のリンクをすべて別ウィンドウ表示にする

[JavaScript] ドメイン外のリンクをすべて別ウィンドウ表示にする

自分のドメイン内はページ内リンク、自分のドメイン外は"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>

こっちの方がいいや。

Home > Programming > [JavaScript] ドメイン外のリンクをすべて別ウィンドウ表示にする

My Friend Feed

http://friendfeed.com/daruyanagi

Google Analyticator

608
 Unique Visitors 
 (1 day) 
Powered By Google Analytics

Return to page top