打开除域之外在新选项卡中打开的所有外部链接

Open all external links open in a new tab apart from a domain

本文关键字:链接 外部 新选项 选项      更新时间:2023-09-26

我正试图在一个新窗口中打开网站上的所有外部链接。然而,网站有两个版本,例如商店和主网站。因此,在主网站上,我们可能会有链接http://store.example.com例如

我在这里有一些代码,可以在一个新窗口中打开所有外部链接。但是,我希望能够排除某些域。就像我上面提到的那个。

这是代码:

$(document).ready(function() {
   $("a[href^=http]").each(function(){
      if(this.href.indexOf(location.hostname) == -1) {
         $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
         });
      }
   })
});

我是JS/jQuery的新手,所以任何其他信息都会非常棒。

为了以编程方式触发点击,您可以执行以下操作:

$(document).ready(function() {
   $("a[href^=http]").each(function(){
      // NEW - excluded domains list
      var excludes = [
         'excludeddomain1.com',
         'excludeddomain2.com',
         'excluded.subdomain.com'
      ];
      for(i=0; i<excludes.length; i++) {
         if(this.href.indexOf(excludes[i]) != -1) {
            return true; // continue each() with next link
         }
      }
      if(this.href.indexOf(location.hostname) == -1) {
           // attach a do-nothing event handler to ensure we can 'trigger' a click on this link
           $(this).click(function() { return true; }); 
           $(this).attr({
               target: "_blank",
               title: "Opens in a new window"
           });
           $(this).click(); // trigger it
      }
   })
});

如果你只想要所有与你的域名不匹配的链接:

var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++){
       var a = all_links[i];
       if(a.hostname != location.hostname) {
               a.rel = 'noopener';
               a.target = '_blank';
       }
}

您是否能够编辑HTML以获得更好的挂钩,用于点击事件?如果我需要在内部或外部之间分离某些链接,我会在HTML元素上应用rel值。

    <a href="URL" rel="external">Link</a>

然后在您的javascript 中

    $('a[rel="external"]').click( function(event) {
     event.stopPropagation();
     window.open( $(this).attr('href') );
     return false;
    });

编辑:既然你已经有很多链接了,这个怎么样。。

    var a = new RegExp('http:'/'/store.blah.com');
    $('a').each(function() {
      if(a.test(this.href)) {
        $(this).click(function(event) {
         event.preventDefault();
         event.stopPropagation();
         window.open(this.href, '_blank');
        });
      }
    });

很抱歉使用了线程亡灵术,谷歌把我带到了这里。我遇到了一个类似的问题,最终解决了这个问题:

document.body.addEventListener('click', function (e) {
  if (e.target.tagName !== 'A') return;
  if (e.target.hostname === location.hostname) return;
  if(['stackoverflow.com','someothersite.com'].indexOf(e.target.hostname) !== -1) return; 
  e.preventDefault();
  window.open(e.target.href);
  return false;
});

我想我会这样做:

    $(document).ready(function() {
      $("a[href^=http]").each(function(){
         if(this.href.indexOf(location.hostname) == -1 && this.href.indexOf("store.domain.com") == -1 && this.href.indexOf("other.domain.rule") == -1) {
            $(this).attr({
               target: "_blank",
               title: "Opens in a new window"
           });
         }
       })
    });

这有点手动,但是,如果您不想处理拆分字符串和数组的问题,这就是解决方案。我相信这会有所帮助。

编辑:除此之外,您还可以使用techfoobar的解决方案来触发链接点击。这将帮助您提高网站性能。

按照techfoobar的回复,您可以构建一个域列表,这些域应该在同一窗口中打开。通过使用正则表达式,您可以用一种更健壮的方式来实现它。如果你只是直接检查indexOf(),你会跳过那些有匹配子域但没有匹配域的链接,尽管如果你想在href字符串中的任何位置匹配名称,你可以省略'$'。

这个实现应该做你想要做的事情,并且对你需要的代码进行最小的修改。

$(document).ready(function() {
    //populate this list with whatever domain names you want, the 
    //$ sign matches the end of the string, only top level domains are affected
    var whiteList = [/google.com'/$/, /stackoverflow.com'/$/];
   $("a[href^=http]").each(function(){
      if(this.href.indexOf(location.hostname) == -1) {
        //check if the href of the current link matches any of our patterns
        var href = this.href;
        if(whiteList.filter(function(x){return x.test(href)}).length == 0) {
         $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
         });
        }
      }
   })
});

在这个例子中,所有指向google.com和stackoverflow.com的链接都将在现有页面中打开。

如果您宁愿在body上使用事件处理程序也不愿更改dom,我建议您这样做。。。

  // open external links in a new tab
  $('body').on('click','a',function(){
    var $a = $(this);
    var href = $a.attr('href');
    if (href.indexOf('/') == 0) return;  // ignore relative links
    var target = $a.attr('target') || "";
    if (target.length > 0) return; // ignore links with a target attribute already
    window.open(href, '_blank');  // open external links in a new tab
    return false;
  });

这将为所有使用PHP 的外部域提供技巧

$(document).ready(function() {
   $("a[href^=http]").each(function(){
      // NEW - excluded domains list
      var excludes = [
         '<?php echo $_SERVER['HTTP_HOST']; ?>'
      ];
      for(i=0; i<excludes.length; i++) {
         if(this.href.indexOf(excludes[i]) != -1) {
            return true; // continue each() with next link
         }
      }
      if(this.href.indexOf(location.hostname) == -1) {
           // attach a do-nothing event handler to ensure we can 'trigger' a click on this link
           $(this).click(function() { return true; }); 
           $(this).attr({
               target: "_blank",
               title: "Opens in a new window"
           });
           $(this).click(); // trigger it
      }
   })
});

基于原始JS中Collin的答案,这非常好,因为它不需要Jquery(尽管OP有问题)。我会修改它,使其能够排除当前主机名以外的域:

    var all_links = document.querySelectorAll('a');
    var excludes = ['domain1.com','www.domain1.com','domain2.com'];
    for (var i = 0; i < all_links.length; i++){
        var a = all_links[i];
        var found = false; 
        for(j=0; j<excludes.length; j++) {
                if(a.href.includes(excludes[j])) {
                    found = true;
                    break;  
                }
        }    
        if (!found) {
            a.rel = 'noopener'; a.target = 'external';
        }
    }