Search code examples
phpjoomla

Automatically add target="_blank" to all external links in joomla components


I have developed a component for Joomla! I am now looking for a solution that can automatically add target="_blank" to all external links in this component.

How can I do this?

Thanks


Solution

  • Using javascript, iterate all anchor link, check if href is external, then add target

    
    function isExternal(url) {
        var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
        if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) return true;
        if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":("+{"http:":80,"https:":443}[location.protocol]+")?$"), "") !== location.host) return true;
        return false;
    }
    
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
        // Add target to anchor link
        if (isExternal(anchors[i].href)) {
        anchors[i].target = "_blank";
        }
    }