Using jQuery to check if a link is internal or external

后端 未结 8 880
南旧
南旧 2020-12-29 09:29

I want to write a script which can determine whether a link is internal or external. This is simple from my perspective, all internal links are relative, so they start with

相关标签:
8条回答
  • 2020-12-29 10:03

    try it

    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
    
    0 讨论(0)
  • 2020-12-29 10:07

    Select only anchors that point back to your domain when the href is the FULL URL.

    jQuery("a:not([href^='http://']), " +
            "a[href^='http://localhost.com'], " +
            "a:not([href^='http://localhost.com/wp-admin'])").addClass("internal");
    
    0 讨论(0)
  • 2020-12-29 10:07

    I prefer this selector myself, it protects against false positives for absolute links that point to your site (like those often generated by a CMS system).

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

    Here's the use case where this worked for me, for context:

    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]);
    });
    
    0 讨论(0)
  • 2020-12-29 10:08
    $(document).ready( function() {
    $('a[href^="http"]').not('a[href^="http://' + $(location).attr('hostname') + 
    '"]').attr('target', '_blank');
    });
    

    Replace "http" with "https" if you need to

    0 讨论(0)
  • 2020-12-29 10:09

    I use this one to find all urls pointing to domain other than current domain or one with (html5 deprecated) 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');   
        })
    
    
    
    }();
    
    0 讨论(0)
  • 2020-12-29 10:12

    I'm using WordPress for my CMS, and so most (if not all) of my internal links start with "http". I found a pretty interesting solution here: http://www.focal55.com/blog/jquery-tutorial-add-class-all-outbound-links-your-site

    In case that site is down, it basically boils down to this selector (I modified it a bit):

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

    Note that this selector will not be the fastest according to the jQuery docs.

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