Skip to content

Instantly share code, notes, and snippets.

@joegaffey
Last active January 25, 2023 15:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joegaffey/46a44c45399afb5f89efef9d1bd5f247 to your computer and use it in GitHub Desktop.
Save joegaffey/46a44c45399afb5f89efef9d1bd5f247 to your computer and use it in GitHub Desktop.
Render items from an RSS feed into a web page.
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);
@joegaffey
Copy link
Author

Updated with pubDate rendering.

@joegaffey
Copy link
Author

joegaffey commented Jan 4, 2023

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