skip to content
Tushar's Avatar Tushar Tripathi

Added Giscus for comments and reactions(Astro App)

I was planning to add utterances but came across Giscus which is based on Github Discussions instead of issues. It also has a bunch of other nice features, and was easy enough to integrate. I created a new github repo to host the comments.

The only tricky part was changing the theme dynamically, I wanted the comments theme to change instantly, if the global theme changes. I tried with just changing the prop passed to the iframe tag, but that wasn’t enough. I checked the docs, and found out that we also need to send a message to the iframe. Anyway, here is the final Astro component I’m using -


GiscusComments.astro
<script>
function updateGiscusTheme() {
const theme = document.documentElement.getAttribute('data-theme');
const giscusTheme = theme === 'light' ? 'light' : 'noborder_gray';
document.getElementById('giscusComments')?.setAttribute('data-theme', giscusTheme);
const iframe = document.querySelector('iframe.giscus-frame') as HTMLIFrameElement;
if (!iframe) return;
const themeMsg = {
setConfig: {
theme: giscusTheme,
reactionsEnabled: false,
}
}
iframe.contentWindow?.postMessage({ giscus: themeMsg}, 'https://giscus.app');
}
updateGiscusTheme();
// Watch for theme changes
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.attributeName === 'data-theme') {
updateGiscusTheme();
}
}
);
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme']
});
</script>
<script src="https://giscus.app/client.js"
id="giscusComments"
data-repo="triptu/comments"
data-repo-id="<unique id from Giscus>"
data-category="Announcements"
data-category-id="DIC_kwDONvjmlc4CmV06"
data-mapping="pathname"
data-strict="0"
data-reactions-enabled="1"
data-emit-metadata="0"
data-input-position="top"
data-lang="en"
crossorigin="anonymous"
data-theme="noborder_gray"
async>
</script>