Last active
January 25, 2023 15:45
-
-
Save joegaffey/46a44c45399afb5f89efef9d1bd5f247 to your computer and use it in GitHub Desktop.
Render items from an RSS feed into a web page.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const LOCAL_FEED_URL = `./feed.rss`; | |
const FEED_ERROR_TXT = `Feed unavailble, check back later`; | |
const postsEl = document.querySelector('.posts'); | |
function showRSS(RSS_URL) { | |
fetch(RSS_URL) | |
.then((response) => { | |
if (response.ok) { return response.text(); } | |
else throw new Error('Something went wrong'); }) | |
.then(str => new window.DOMParser().parseFromString(str, "text/xml")) | |
.then(data => { | |
const items = data.querySelectorAll("item"); | |
let html = ``; | |
items.forEach(el => { | |
const titleEl = el.querySelector("title"); | |
const categoryEl = el.querySelector("category"); | |
const linkEl = el.querySelector("link"); | |
const pubDate = new Date(el.querySelector("pubDate").innerHTML).toDateString(); | |
const title = titleEl ? titleEl.innerHTML : pubDate; | |
const link = linkEl.innerHTML; | |
const category = categoryEl ? categoryEl.innerHTML : 'Link'; | |
const description = getDescription(el.querySelector("description").innerHTML); | |
html += ` | |
<article> | |
<h3>${title} [<a href="${link}">${category}</a>]</h3> | |
${(title == pubDate) ? `` : `<h4>${pubDate}</h4>`} | |
<p>${description}</p> | |
</article> | |
`; | |
}); | |
postsEl.innerHTML = html; | |
}) | |
.catch(e => { postsEl.innerHTML = `<h3>${FEED_ERROR_TXT}</h3>`; }); | |
} | |
function getDescription(textIn) { | |
let doc = new DOMParser().parseFromString(textIn, "text/html"); | |
doc = new DOMParser().parseFromString(doc.documentElement.textContent, "text/html"); | |
const aElList = doc.querySelectorAll("a"); | |
aElList.forEach(el => { // Shorten URLs | |
if(el.innerText.startsWith('https://')) | |
el.innerText = el.href.substring(8, 26) + '...'; | |
}); | |
const pEl = doc.querySelector("p"); | |
return pEl ? `<p>${pEl.innerHTML}</p>` : textIn; | |
} | |
showRSS(LOCAL_FEED_URL); |
Updated with error handling, url shortening and support for Mastodon's RSS structure.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated with pubDate rendering.