# 在页面头部的Discourse Gamification插件

**URL:** https://meta.discourse.org/t/discourse-gamification-plugin-in-the-header/354769
**Category:** Development
**Created:** [2025年二月27日 06:36 UTC](https://meta.discourse.org/t/discourse-gamification-plugin-in-the-header/354769 "2025-02-27T06:36:06Z")
**Posts on this page:** 1
**Showing post:** 20

<div class="post-metadata">

### Author: ![TRgala\_Murat](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/trgala_murat/32/484588_2.png) [@TRgala\_Murat](https://meta.discourse.org/u/TRgala_Murat)
#### Post date: [2025年二月28日 09:06 UTC](https://meta.discourse.org/t/discourse-gamification-plugin-in-the-header/354769/20 "2025-02-28T09:06:54Z")

</div>

这是一个临时但有用的方法。也许他们想改进它，我把代码放在这里

测试网站：[https://trgala.com](https://trgala.com/)

Js

```plaintext
import { apiInitializer } from "discourse/lib/api";

export default apiInitializer("0.8", (api) => {
    api.onPageChange(() => {
        const currentUser = api.getCurrentUser();
        if (!currentUser) {
            console.warn("用户未登录");
            return;
        }

        fetch(`/u/${currentUser.username}.json`)
            .then(response => response.json())
            .then(data => {
                console.log("游戏化数据：", data);
                let score = data?.user?.gamification_score ?? 0;

                // 如果分数框已存在，则不再添加
                if (document.querySelector("#gamification-score")) return;

                // 查找标题的 .contents 容器
                let headerContents = document.querySelector(".d-header> .wrap .contents");
                if (headerContents) {
                    // 创建分数框
                    let scoreContainer = document.createElement("a");
                    scoreContainer.id = "gamification-score";
                    scoreContainer.classList.add("gamification-box");
                    scoreContainer.href = "website";
                    scoreContainer.target = "_blank"; // 在新标签页中打开

                    // 金币图标
                    let icon = document.createElement("span");
                    icon.innerText = "T";
                    icon.classList.add("gold-icon");

                    // 分数文本
                    let scoreText = document.createElement("span");
                    scoreText.innerText = `${score}`;
                    scoreText.classList.add("gold-text");

                    // 将图标和文本添加到框中
                    scoreContainer.appendChild(icon);
                    scoreContainer.appendChild(scoreText);

                    // 将框添加到标题中
                    headerContents.appendChild(scoreContainer);
                }
            })
            .catch(error => console.error("获取游戏化分数时出错：", error));
    });
});

```

---

_[View the full topic](https://meta.discourse.org/t/discourse-gamification-plugin-in-the-header/354769)._
