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

当然,写代码还是得先AI驱动。
核心属性
必须开启
| 属性 | 值 | 说明 |
|---|---|---|
data-emit-metadata | 1 | 必须开启,否则不会发送评论数信息 |
选择字段,需要那个用哪个。
| 字段 | 含义 |
|---|---|
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,他就知道怎么配合你的编程语言和框架来修改代码了。
