v i b e Scriptz

External-link highlighter (with ↗ icon + rel fixes)

November 30, 2025 NEW

Tags: external links security javascript ux

What this snippet does

This snippet walks your page looking for links that go off-site and:

No dependencies, no build tools — just vanilla JS and a couple of CSS rules.

<style>
  /* Style for external links */
  a.vibe-external {
    position: relative;
    text-decoration: none;
  }

  a.vibe-external::after {
    content: "↗";
    display: inline-block;
    margin-left: 0.25em;
    font-size: 0.8em;
    opacity: 0.75;
    vertical-align: baseline;
  }

  a.vibe-external:hover::after {
    opacity: 1;
  }
</style>

<script>
  (function () {
    // Set this to false if you DON'T want new tabs
    var OPEN_IN_NEW_TAB = true;

    var currentHost = window.location.hostname.replace(/^www\./i, '');

    var links = document.querySelectorAll('a[href^="http"]:not([data-no-external])');

    links.forEach(function (link) {
      try {
        var url = new URL(link.href);
        var linkHost = url.hostname.replace(/^www\./i, '');

        // Treat same host as internal
        if (linkHost === currentHost) {
          return;
        }

        // Mark as external for styling
        link.classList.add('vibe-external');

        // Security: make sure rel is set
        var rel = (link.getAttribute('rel') || '').split(/\s+/).filter(Boolean);
        if (rel.indexOf('noopener') === -1) rel.push('noopener');
        if (rel.indexOf('noreferrer') === -1) rel.push('noreferrer');
        link.setAttribute('rel', rel.join(' '));

        // Optional: open external links in a new tab
        if (OPEN_IN_NEW_TAB) {
          link.setAttribute('target', '_blank');
        }
      } catch (e) {
        // If URL parsing fails for some reason, just skip that link
      }
    });
  })();
</script>

How to use it

  1. Paste the <style> and <script> snippet into your base layout (footer, shared template, or theme file).
  2. By default, any link starting with http that doesn’t point to your current hostname will get: class="vibe-external", a ↗ icon, and rel="noopener noreferrer".
  3. If you have a special link you do not want treated as external, add data-no-external to it:
    <a href="https://example.com" data-no-external>Leave me alone</a>

You can tweak the icon in content: "↗" (for example, use "⧉") or change the behavior of OPEN_IN_NEW_TAB if you prefer external links not to open new windows.

← Back to all scripts