Using jQuery to check if a link is internal or external

后端 未结 8 937
南旧
南旧 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: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]);
    });
    

提交回复
热议问题