【问题标题】:Automatically add target="_blank" to all external links in joomla components自动将 target="_blank" 添加到 joomla 组件中的所有外部链接
【发布时间】:2021-02-12 12:13:27
【问题描述】:

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

我该怎么做?

谢谢

【问题讨论】:

  • 请在Joomla Stack Exchange 上询问您的 Joomla 问题。如果我们可以更仔细地查看您的组件,可能会有一种不那么老套的方法来解析您的标记并提供一个健壮的解决方案。

标签: php joomla


【解决方案1】:

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

【讨论】:

  • 这个问题似乎在寻求php的解决方案。
猜你喜欢
  • 2012-08-16
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 2012-06-25
  • 2011-08-18
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多