A simple webmention comment section
Heya!
I made a simple webmention comment section.
This comment section assumes youre using webmentions.io for receiving webmentions, which anyone on bearblog probably is because you cant do em serverside here.
The comment section is completely unstyled by default, youll have to do that part yourself.
To use this, you need two things:
- The javascript. Add this to your header or footer
function getWebmentionsFromUrl() {
return fetch(`https://webmention.io/api/mentions.jf2?target=${window.location.href}`)
.then((response) => {
return response.json().then((data) => {
return data;
}).catch((err) => {
console.log(err);
})
});
}
class WebmentionComments extends HTMLElement {
constructor() {
super();
}
async connectedCallback() {
const webmentions = await getWebmentionsFromUrl();
if(webmentions.count <= 0) {
this.innerHTML = '<div class="webmention-no-results">No comments yet!</div>'
return;
}
webmentions.children.forEach(mention => {
// I know this is a tad scuffed, but who cares
let authorName = ""
if(mention.author.name) {
authorName = `<p>${mention.author.name}</p>`
} else {
let authorUrl;
authorUrl = new URL(mention.url);
authorName = authorName = `<p>${authorUrl.hostname} linked to this post:</p>`
}
let authorPfp = ""
if(mention.author.photo) {
authorPfp = `<img class="webmention-author-pfp" src="${mention.author.photo}">`
}
let authorUrl = ""
if(mention.author.url) {
authorUrl = `<a class="webmention-author-url" href="${mention.author.url}">${mention.author.url}</a>`
}
let mentionContent = ""
if(mention.content) {
mentionContent = `
<div class="webmention-info-content">
${mention.content.text}
</div>`
}
let mentionInfoUrl = ""
if(mention.url) {
mentionInfoUrl = `<a class="webmention-info-url" href="${mention.url}">${mention.url}</a>`
}
let mentionPublished = ""
if(mention.published) {
mentionPublished = `<time class="webmention-info-published">${mention.published}</time>`
}
this.innerHTML += `<div class="webmention-comment">
<div class="webmention-author">
${authorName}
${authorPfp}
${authorUrl}
</div>
<div class="webmention-info">
${mentionContent}
${mentionInfoUrl}
${mentionPublished}
</div>
</div>`
});
}
}
customElements.define("webmention-comments", WebmentionComments);
- The html. Add this to the blogpost you want to show webmentions on.
<link rel="webmention" href="https://webmention.io/your.website/webmention" />
<webmention-comments></webmention-comments>