Its simple (well, to implement anyway):

  • Go to Theme
    • Head HTML Injection
      • Add this script:
<script>
  document.addEventListener("DOMContentLoaded", function() {
    const observer = new MutationObserver(() => {
      const links = document.querySelectorAll('a');
      const currentDomain = window.location.hostname;

      links.forEach(link => {
        const linkHost = new URL(link.href).hostname;
        if (linkHost !== currentDomain && link.hostname !== "") {
          link.setAttribute('target', '_blank');
          link.setAttribute('rel', 'noopener noreferrer');
        }
      });
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  });
</script>

You probably almost implemented something similar. The issue here though, is wiki.js requires this to be implemented in a slightly different way. The javascript snip above does the following:

Ensures that links to other websites open in a new tab and are secure. In short:

  1. Page Load: Waits until the webpage loads.
  2. Observer: Sets up a watcher to monitor webpage changes.
  3. Find & Check Links: Locates all links and checks if they go to a different website.
  4. Update Links: If the link is external, it opens in a new tab with added security.
  5. Keep Watching: Continues monitoring for new links and repeats the process.

The reason for the mutationobserver is because some of the links may not be loaded yet at the time of page render; This code will detect the changes as they happen and respond accordingly without having to constantly check the entire DOM manually.

Enjoy!

[Here’s what it looks like in action]:

Leave a Reply

Your email address will not be published. Required fields are marked *