0

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

Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
  • 1
    Please ask your Joomla questions on [joomla.se] Stack Exchange. If we can have a closer look at your component, there may be a less hacky way to parse your markup and provide a robust solution. – mickmackusa Oct 30 '20 at 15:50

1 Answers1

0

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";
    }
}

Illya
  • 1,268
  • 1
  • 5
  • 16