Open external links in a new tab without jQuery

前端 未结 3 592
挽巷
挽巷 2020-12-30 10:27

What\'s the best way to open all external links (URLs that don\'t match the current domain) in a new tab using JavaScript, without using jQuery?

Here\'s the jQuery I

相关标签:
3条回答
  • 2020-12-30 11:18

    Pure JS:

    function externalLinks() {
      for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
        var b = c[a];
        b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
      }
    }
    ;
    externalLinks();
    
    0 讨论(0)
  • 2020-12-30 11:18
           $("a[href^=http]").each(function(){
              if(this.href.indexOf(location.hostname) == -1) {
                 $(this).attr({
                    target: "_blank",
                    title: "Opens in a new window"
                 });
              }
           })
    

    This script should work for you.

    UPDATE : try this fiddle http://jsfiddle.net/sameerast/GuT2y/

    JS version

        var externalLinks = function(){
          var anchors = document.getElementsByTagName('a');
          var length = anchors.length;
          for(var i=0; i<length;i++){
            var href = anchor[i].href;
            if(href.indexOf('http://sample.com/') || href.indexOf('http://www.sample.com/')){
              return;
            }
            else{
              anchor[i].target='_blank';
            }
          }
        };
    
    0 讨论(0)
  • 2020-12-30 11:19

    Add a target="_blank" to the tag. You could do that in the pre-processor (e.g. PHP) or in a JS during the onload event.

    0 讨论(0)
提交回复
热议问题