joomla组件中所有外部链接自动添加target="_blank"
Automatically add target="_blank" to all external links in joomla components
我已经为 Joomla! 开发了一个组件!我现在正在寻找一种解决方案,可以自动将 target="_blank"
添加到该组件中的所有外部链接。
我该怎么做?
谢谢
使用javascript,迭代所有锚点link,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";
}
}
我已经为 Joomla! 开发了一个组件!我现在正在寻找一种解决方案,可以自动将 target="_blank"
添加到该组件中的所有外部链接。
我该怎么做?
谢谢
使用javascript,迭代所有锚点link,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";
}
}