How to open external links in a new tab/window by default?

Last modified by Vincent Massol on 2020/04/24

In order to configure all external links to open in new tabs/windows automatically, i.e. to use the link target "_blank" from an HTML point of view, you have to add some JavaScript to your XWiki.

How you are generating your external links will dictate which of the two snippet options you choose.

XWiki Syntax
If you are only generating your external links via XWiki Syntax, you will use Option 1 on Step 4.

HTML Links
If you are writing any external links directly in HTML, either through the {{html}} macro or in a Velocity .vm file, you have two options:

  • Use Option 1 on Step 4 and manually wrap your links in an element with the wikiexternallink class.
    • Will not work: <a href="https://www.xwiki.org">XWiki</a>
    • Will work: <span class="wikiexternallink"><a href="https://www.xwiki.org">XWiki</a></span>
  • No modifications need to be made to existing HTML. Instead, use Option 2 on Step 4.

Steps

Your user type should be advanced to be able to follow the steps. Go to "Profile Settings > Preferences > USER TYPE" for changing the user type to advanced.

  1. Create a new page, or go to an existing page that won’t be removed.
  2. Click Edit and select Objects.
  3. In the Select a Class box, select JavaScriptExtension and click the Add button.
  4. In the object that just appeared, enter one of the following snippets into the Code box (explained above):1. If you are using only XWiki Syntax for your external links:

    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. If you have any external links in HTML a elements:
      require(['jquery'], function($) {
        jQuery(document.links).filter(function() {
         return this.hostname != window.location.hostname;
        }).attr('target', '_blank');
      });
  5. Set Use this extension to On this wiki.

Thanks to pdwalker and laurin1 for this solution.

Get Connected