[solved] External links, set default target as "_blank"

Works in IE and Chrome:

  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);
1 Like

Thanks.

I would have gotten to it eventually, but this just save me a whole lot of time.

And since you mentioned it, I’ll reexamine edge to see how well it behaves in our environment. :wink:

1 Like

I just tried to reproduce the solution in the current version of xwiki. Unfortunately, (parts of ?) the code is just shown at the top of the wiki and does not solve the problem anymore

browser is firefox (newest) and chrome (newest)

You’ll have to be more specific about what you actually did so we can figure out where it is going wrong for you.

The above solution continues to work for me.

Specifically, I implemented the following under Administration, Look & Feel, Presentation, HTTP Meta Info:
Screenshot 2022-09-18 at 01.11.29

<script>
  function fixExternalLinks() {
    document.querySelectorAll('.wikiexternallink a').forEach(function(link) { 
      if (link.hasAttribute('target') == false)  {
        link.setAttribute('target', '_blank');
      }
    })
  }
  document.addEventListener("DOMContentLoaded", fixExternalLinks);
</script>

Basically, the javascript code code executes once the page is loaded, looks for any external links and if they do not already have a target specified, gives it a _blank target.

1 Like

I’m embarrassed to say that I never got back to this since the javascript injection was working so well.

bam, sorry. I don’t know what was happening but I tried it again and now it is working like a charm. Thanks you!