Redirect Page for External URLs

What you’re looking for is called a post decorator. It’s a hook that allows you to run scripts before each post is rendered. It’s a part of the plugin API.

Now, regarding what you want to do (redirect all external links). I don’t think adding that much friction is a good idea, so I can’t help you with that - plus you already figured that bit out. That said, here’s a commented example of how you can create a setup that targets all external links in posts

This goes in the header section of your theme / theme component

<script type="text/discourse-plugin" version="0.8">
  // store the hostname so we can reuse it.
  const siteHostname = location.hostname;
  
  // let's create a decorator to do this in every post
  api.decorateCooked(
    post => {
      // does the post have links?
      const links = [...post[0].querySelectorAll("a")];
      
      // no links, bail.
      if (!links.length) return;
      
      // We have links, let's filter them and only grab the ones that are external
      const externalLinks = links.filter(
        link => link.hostname !== siteHostname
      );
      
      // if we have some external links, let's do some work. For example, we can
      // add a class to each external link like so.
      externalLinks.forEach(link => {
        link.classList.add('external-link');
        // do more work here.
      });
    },
    // we give our decorator an id to prevent memory leaks.
    { id: "external-link-decorator" }
  );
</script>

Again, redirecting users is too much friction and will get annoying real fast. So, I would consider another approach, like maybe adding a subtle icon next to external links and teaching your users what it means instead?

5 Likes