Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to add your latest Mastodon toot to your sidebar
<!--
1. Put the following HTML in your sidebar.php (or wherever you fancy)
-->
<p class="toot h-entry">
<span class="e-content"></span>
<a class="u-url" href>
<time class="dt-published" datetime></time>
</a>
</p>
<!--
2. Put the following <script> tags in your footer.php before </body> and
replace "USERNAME" with your Mastodon username. Of note, there's a
dependency on the date-fns library: https://date-fns.org for date formatting.
Choose your own format: https://date-fns.org/v1.29.0/docs/format
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.js"></script>
<script>
fetch('https://mastodon.social/@USERNAME.rss').then(function (response) {
return response.text();
}).then(function (xml) {
const parser = new DOMParser().parseFromString(xml, "text/xml");
// get the bits we need from the RSS feed
const item = parser.getElementsByTagName('item')[0];
const descriptionFromFeed = item.getElementsByTagName('description')[0].textContent;
const timeFromFeed = item.getElementsByTagName('pubDate')[0].textContent;
const permalinkFromFeed = item.getElementsByTagName('guid')[0].textContent;
// hack to get the description content from <p> tags
const tempDiv = document.createElement("div");
tempDiv.innerHTML = descriptionFromFeed;
const descriptionFromFeedText = tempDiv.textContent || tempDiv.innerText;
// write to HTML
document.querySelector('.toot .e-content').innerHTML = descriptionFromFeedText;
document.querySelector('.toot .u-url').href = permalinkFromFeed;
document.querySelector('.toot .dt-published').setAttribute("datetime", dateFns.format(timeFromFeed, 'YYYY-MM-DDTHH:mm:ssZ'));
document.querySelector('.toot time').innerHTML = dateFns.format(timeFromFeed, 'DD MMM @ HH:mm');
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment