ヘッダーに Discourse Gamification Plugin

一時的ですが便利な方法です。改善したいのかもしれません。コードをここに残しておきます。

テストウェブサイト: https://trgala.com

Js

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));
    });
});
「いいね!」 4