自动将target =“ _ blank”添加到joomla组件中的所有外部链接

问题描述

我已经为Joomla开发了一个组件!我现在正在寻找一种可以自动向该组件中的所有外部链接添加target="_blank"解决方案。

我该怎么做?

谢谢

解决方法

使用JavaScript,迭代所有锚点链接check if href is external,然后添加目标


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