# 外部 URL 的重定向页面

**URL:** <https://meta.discourse.org/t/redirect-page-for-external-urls/146798>\
**Category:** Support\
**Created:** [2020年四月4日 10:14 UTC](https://meta.discourse.org/t/redirect-page-for-external-urls/146798 "2020-04-04T10:14:21Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)\
**Post date:** [2020年四月6日 07:43 UTC](https://meta.discourse.org/t/redirect-page-for-external-urls/146798/14 "2020-04-06T07:43:16Z")

</div>

> [@CRUGG](#):
>
> 但我仍然在摸索如何在页面加载完成且所有动态内容（例如帖子）都已加载 **之后** 运行 JS 代码。一个临时的解决方案是在 1-2 秒后运行代码，但这并不是很理想，而且对某些人来说，加载时间可能会更长……

你正在寻找的功能被称为“帖子装饰器”（post decorator）。它是一个钩子，允许你在每个帖子渲染之前运行脚本。它是 [插件 API](https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/lib/plugin-api.js) 的一部分。

现在，关于你想做的事情（重定向所有外部链接）。我认为增加这么多摩擦并不是个好主意，所以我无法在这方面帮助你——况且你已经自己解决了那部分问题。不过，这里有一个带注释的示例，展示如何创建一个针对帖子中所有外部链接的设置。

这段代码应放在你的主题/主题组件的 `header` 部分：

```markdown
<script type="text/discourse-plugin" version="0.8">
  // 存储主机名以便重复使用。
  const siteHostname = location.hostname;
  
  // 让我们创建一个装饰器，在每个帖子中执行此操作
  api.decorateCooked(
    post => {
      // 帖子中有链接吗？
      const links = [...post[0].querySelectorAll("a")];
      
      // 如果没有链接，直接退出。
      if (!links.length) return;
      
      // 有链接，让我们过滤它们，只获取外部链接
      const externalLinks = links.filter(
        link => link.hostname !== siteHostname
      );
      
      // 如果有外部链接，我们可以做一些处理。例如，我们可以
      // 为每个外部链接添加一个类，如下所示。
      externalLinks.forEach(link => {
        link.classList.add('external-link');
        // 在这里做更多处理。
      });
    },
    // 我们给装饰器一个 ID 以防止内存泄漏。
    { id: "external-link-decorator" }
  );
</script>

```

再次强调，重定向用户会带来太多摩擦，很快就会让人厌烦。因此，我建议你考虑其他方法，比如在外部链接旁边添加一个微妙的图标，并教导你的用户其含义，怎么样？

 ![外部链接旁的图标](https://global.discourse-cdn.com/meta/original/3X/f/2/f28ed837cf3855617e7f7195c5bcb849d07a73c0.png)

---

_[View the full topic](https://meta.discourse.org/t/redirect-page-for-external-urls/146798)._
