需要从接收此通知中排除某些外部链接

时间:2017-01-25 16:23:43

标签: jquery notifications

我使用此代码通知用户他们要访问第三方网站,但我想排除一些外部网址。我在这段代码中如何/在哪里做到这一点?

<script>
   $('a').each(function() {
      if (this.href !== "#" && this.href.indexOf('/') !== 0 && this.href.indexOf(location.hostname) === -1) {
        $(this).attr('target', '_blank')
          .click(function() {        return confirm('NOTICE: You are leaving our website and will enter a website maintained by a third party. We are providing a link to the third party website solely as a convenience to you, because we believe that website may provide useful content. We are not, by referring or linking to the third party website, incorporating its contents into our own website. We do not endorse or guarantee, and we disclaim any responsibility for: the content, products or services offered on that website, its performance or interaction with your computer, its security and privacy policies and practices, and any consequences that may result from visiting that website. By clicking OK, you acknowledge this statement.');
       });
      }
    });
});
</script>

1 个答案:

答案 0 :(得分:0)

您需要检查该网站是否在白名单中。因此,您需要创建一些内容,以便在站点时检查列表。

我还建议您将逻辑提取到函数中,以使其更容易维护。

  function IsNoticeRequired(url)
  {      
      // Makes dealing with exclusions easier.
      url = url.toLowerCase();

      // Put the white listed sites here.
      var excludedSites = 
      [
          "stackoverflow.com"       
      ];

      // Determine if the site is in the exclusion list.
      var isInExclusion = false;
      for(var i = 0; i < excludedSites.length; i++)
      {
          // Need to check if url contains site.
          if(url.indexOf(excludedSites[i]) !== -1)
          {
              isInExclusion = true;
              break;
          }
      }

      var isNoticeRequired = url !== "#";
      isNoticeRequired = isNoticeRequired && url.indexOf("/") !== 0
      isNoticeRequired = isNoticeRequired && url.indexOf(location.hostname) === -1;
      isNoticeRequired = isNoticeRequired && !isInExclusion;

      return isNoticeRequired;
  }

$('a').each(function() {
  if (IsNoticeRequired(this.href)) {
    $(this).attr('target', '_blank')
      .click(function() {        return confirm('NOTICE: You are leaving our website and will enter a website maintained by a third party. We are providing a link to the third party website solely as a convenience to you, because we believe that website may provide useful content. We are not, by referring or linking to the third party website, incorporating its contents into our own website. We do not endorse or guarantee, and we disclaim any responsibility for: the content, products or services offered on that website, its performance or interaction with your computer, its security and privacy policies and practices, and any consequences that may result from visiting that website. By clicking OK, you acknowledge this statement.');
   });
  }
});

JSFiddle of it in action:https://jsfiddle.net/9n7v67xa/