【问题标题】:Using jQuery to check if a link is internal or external使用 jQuery 检查链接是内部链接还是外部链接
【发布时间】:2021-10-20 18:38:39
【问题描述】:

我想编写一个脚本来确定链接是内部链接还是外部链接。从我的角度来看,这很简单,所有内部链接都是相对的,所以它们以 / 开头。所有外部链接都以 http:// 开头 - 到目前为止一切正常。但是我不知道如何对文本以外的任何内容执行“:contains()” - 如何在属性中搜索字符串?

一旦我能做到这一点,我很乐意自己添加 target _blank,除非你知道更好的方法

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以使用attribute^=value 语法查找以http/ 开头的href:

    $("a[href^='http']") // external
     
    $("a[href^='/']") // internal
    

    这里有一个更好的解决方案:您可以使用下面的插件代码将$('a:external')$('a:internal') 选择器添加到jQuery。任何以 http://https://whatever://// 开头的 URL 都被视为外部 URL。所有其他 URL 都被视为内部 URL。

        $.expr[':'].external = function (a) {
            var PATTERN_FOR_EXTERNAL_URLS = /^(\w+:)?\/\//;
            var href = $(a).attr('href');
            return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
        };
    
        $.expr[':'].internal = function (a) {
            return $(a).attr('href') !== undefined && !$.expr[':'].external(a);
        };
    

    【讨论】:

    • 我说的对吗?内部网址并不总是以正斜杠开头。内部使用 $('a[href!=http:] a[href!=https:]') 可能会更好。
    • 对于我正在做的事情,属性选择器是更好的选择。但是,它们存在一个小问题。它们应该是 $('a[href^="http"]') 和 $('a[href^="/"]')
    • 这会因协议相对 URL 而失败,例如 //www.google.com
    • 你可以用/^(\w+:)?\/\//修复它
    • @landon 好主意。完成。
    【解决方案2】:

    我的 CMS 使用 WordPress,所以我的大部分(如果不是全部)内部链接都以“http”开头。我在这里找到了一个非常有趣的解决方案:http://www.focal55.com/blog/jquery-tutorial-add-class-all-outbound-links-your-site

    万一那个网站宕机了,基本上归结为这个选择器(我稍微修改了一下):

    $( 'a[href^="//"],a[href^="http"]' )
        .not( '[href*="' + window.location.hostname + '"]' )
    ;
    

    请注意,根据 jQuery 文档,此选择器将 not be the fastest

    【讨论】:

    • 很高兴听到这个消息。请记住,在某些极端情况下,这可能会丢失外部链接。像 external.com/?ref=internal.com 这样的东西可能会出错。在我的使用中,我还没有遇到过类似的情况,但很高兴知道。
    【解决方案3】:

    当 href 是 完整 URL 时,仅选择指向您的域的锚点。

    jQuery("a:not([href^='http://']), " +
            "a[href^='http://localhost.com'], " +
            "a:not([href^='http://localhost.com/wp-admin'])").addClass("internal");
    

    【讨论】:

      【解决方案4】:

      我自己更喜欢这个选择器,它可以防止指向您网站的绝对链接的误报(例如那些通常由 CMS 系统生成的链接)。

      var currentDomain = document.location.protocol + '//' + document.location.hostname;
      var outboundLinks = 'a[href^="http"]:not([href*="' + currentDomain + '"])';
      

      这是对我有用的用例,用于上下文:

      var currentDomain = document.location.protocol + '//' + document.location.hostname;
      $('a[href^="http"]:not([href*="' + currentDomain + '"])').on('click', function (e) {
          e.preventDefault();
      
          // track GA event for outbound links
          if (typeof _gaq == "undefined")
              return;
      
          _gaq.push(["_trackEvent", "outbound", this.href, document.location.pathname + document.location.search]);
      });
      

      【讨论】:

        【解决方案5】:

        我使用这个来查找所有指向domain other than current domain 的网址或带有(不推荐使用html5)attribute target="_blank" 的网址

        var contrastExternalLinks =  function() {
            //create a custom external selector for finding external links
            $.expr[':'].external = function( obj ) {
                return (
                    $(obj).attr('target')   &&  $(obj).attr('target') =='_blank' ) 
                        || 
                            (!obj.href.match(/^mailto\:/)   && !obj.href.match(/^tel\:/)    &&  (obj.hostname != location.hostname )
                                );
            };
            // Usage:
            $(document).ready(function() {
                $('a:external').addClass('external');///css('background-color', 'green');   
            })
        
        
        
        }();
        

        【讨论】:

          【解决方案6】:
          $(document).ready( function() {
          $('a[href^="http"]').not('a[href^="http://' + $(location).attr('hostname') + 
          '"]').attr('target', '_blank');
          });
          

          如果需要,将“http”替换为“https”

          【讨论】:

            【解决方案7】:

            我认为简单且不那么令人头疼的方法是不使用纯 javascript 或 jQuery,而是将其与 html 结合起来,然后检查单击的链接是否包含您的基本站点的 url。它适用于任何类型的基本网址(例如:example.com、example.com/site)。如果您需要动态值,那么您只需要使用您喜欢的服务器端编程语言来设置值,例如 PHP、asp、java 等。

            这是一个例子:

            HTML

            <!--Create a hidden input containing your base site's url.-->
            <input type="hidden" id="sitedomain" value="example.com/site"/>
            

            jQuery

            $(".elem").on("click", function(e){
              if($(this).closest("a").length) {
              var url = $(this).attr("href");
              var sitedomain = $("#sitedomain").val();
            
              if(url.indexOf(sitedomain) > -1) {
                alert("Internal");
              } else {
                alert("External");
              }
             }
            });
            

            【讨论】:

              【解决方案8】:

              试试看

              var fullBaseUrl = 'https://internal-link.com/blog';
              
              var test_link1 = 'https://internal-link.com/blog/page1';
              var test_link2 = 'https://internal-link.com/shop';
              var test_link3 = 'https://google.com';
              
              test_link1.split(fullBaseUrl)[0] == ''; // True
              test_link2.split(fullBaseUrl)[0] == ''; // False
              test_link3.split(fullBaseUrl)[0] == ''; // False
              

              【讨论】:

              • 虽然此代码可以回答问题,但提供有关 如何为什么 解决问题的附加上下文将提高​​答案的长期价值。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-03-23
              • 2017-11-23
              • 1970-01-01
              • 2012-02-08
              • 1970-01-01
              相关资源
              最近更新 更多