网页加载的时候获取giscus当前页面的评论数

作者: J.sky
339·预计阅读 2 min read

前几天看到有个博客使用giscus,而且他的文章页打开后可以获得giscus的评论数,很是感兴趣,也就照猫画虎的实现了这个功能。

giscus

当然,写代码还是得先AI驱动。

核心属性

必须开启

属性说明
data-emit-metadata1必须开启,否则不会发送评论数信息

选择字段,需要那个用哪个。

字段含义
totalCommentCount顶级评论数(不含回复)
totalReplyCount回复数
totalCount评论 + 回复 总数

参考代码:

// 评论数获取模块
const GiscusCommentCount = {
    count: 0,
    callback: null,
    
    init(callback) {
        this.callback = callback;
        
        window.addEventListener('message', (event) => {
            if (event.origin !== 'https://giscus.app') return;
            
            const { giscus } = event.data || {};
            if (!giscus) return;
            
            // 获取评论数
            if (giscus.discussion) {
                this.count = giscus.discussion.totalCommentCount;
                if (this.callback) this.callback(this.count);
            }
            
            // 处理错误
            if (giscus.error) {
                console.error('Giscus error:', giscus.error);
                if (this.callback) this.callback(0);
            }
        });
        
        // 超时处理(5秒后仍未获取)
        setTimeout(() => {
            if (this.count === 0 && this.callback) {
                this.callback(0);
            }
        }, 5000);
    }
};

// 使用
GiscusCommentCount.init((count) => {
    const el = document.getElementById('comment-count');
    el.textContent = count > 0 ? `${count} 条评论` : '暂无评论';
});

是坑?

改了半天,貌似只能获取顶级评论数(不含回复) ,获取评论+回复没有调试出来。有没有高人指点下?

总结

你把这些喂给AI,他就知道怎么配合你的编程语言和框架来修改代码了。

本文为原创文章,遵循: CC BY-NC-SA 4.0版权协议。

本文链接:https://www.suiyan.cc/blog/20260130014503

标签: giscus
英雄请留步!欢迎点击图标,留言交流!
赞赏码

相关文章

那年今日