This identifies all external links by comparing them to the current window URL. If the link goes to a different domain, it adds the target="_blank" attribute to its HTML a tag, which will open it in a new window when clicked on.
It might seem elementary to some, but this is what I found that works for me.
@thedelk Actually your implementation is not the best possible. It’s a bit too performance-intensive and it doesn’t need to. You should just look for external links which are identified in the HTML DOM with the “wikiexternallink” class.
@vmassol: Yes, that’s the snipped from the forum thread I linked to and that’s also how I solved it for now - works fine, I just wanted to know if there was any more elegant or “more official” way to do so.
There’s no other way, it’s the recommended way on the web AFAIK. Only thing that could be better for xwiki users is to bundle this script in the XWiki Standard distribution and offer a feature in the Admin UI to configure it. You could create a jira for this if you want (maybe there’s one already?).
Darn. I was going to do it, but I guess @GOhrner woke up earlier than me today.
That snippet does make more sense. I had planned to go back and rewrite some of the objects on my wiki once I got everything in place, so thanks @vmassol for saving me some time!
A quick note, for anyone who may happen upon this post:
This code in the FAQ article will only work if the link has a parent element with the wikiexternallink class.
Summary
function fixExternalLinks() {
var nodes = document.querySelectorAll('.wikiexternallink a');
for(var i=0; i< nodes.length; i++){
var link = nodes[i];
if (link.hasAttribute('target') == false) {
link.setAttribute('target', '_blank');
}
}
}
document.addEventListener("DOMContentLoaded", fixExternalLinks);
These are rendered by default when using Wiki syntax to create the link, e.g. [[http://xwiki.org]] or [[XWiki>>http://xwiki.org]].
However, if you are directly writing HTML, either through the {{html}} macro or directly in a Velocity .vm file, you will need to manually wrap your links in an element with that class. Otherwise, the link has nothing that the snippet can use to identify it as an external link.
You can use the jQuery code to work for all links without having to add the extra parent element. As @vmassol pointed out, it’s not the most performant solution, but the impact is pretty negligible. I tested them both on a page with about 400 external links and saw no difference in load times.
Can this be turned into an extension, that one can install? Even if it consists of a few lines of code, I’d much prefer something to install rather than something I have to manually add.