Skip to content

Instantly share code, notes, and snippets.

@briatte
Created January 6, 2019 11:32
Show Gist options
  • Save briatte/18f7e2ea567f86a80c2ba79d357e99c9 to your computer and use it in GitHub Desktop.
Save briatte/18f7e2ea567f86a80c2ba79d357e99c9 to your computer and use it in GitHub Desktop.
Show RSS feeds on a Web page via pure JavaScript, incl. code to bypass Chrome's CORS policy.
# enable CORS policy
# https://gist.github.com/maxparm/3105526
<IfModule mod_rewrite.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: "Content-Type"
RewriteEngine on
RewriteBase /
</IfModule>
<script type="text/javascript">
document.write('<h4>Blog posts at <a href="/r">R / Notes</a> (in English)</h4>');
document.write('<div class="feed"><ul id="r"></ul></div>');
parse('https://f.briatte.org/r/rss', 'r');
document.write('<h4>Blog posts at <a rel="external" href="https://politbistro.hypotheses.org/">Polit&rsquo;&nbsp;bistro</a> (in French)</h4>');
document.write('<div class="feed"><ul id="politbistro"></ul></div>');
parse('https://politbistro.hypotheses.org/feed', 'politbistro');
</script>
// based on https://github.com/pokiiio/hatena-blog-parser
function parse(rssUrl, rssList) {
const request = new XMLHttpRequest();
request.open('GET', rssUrl);
request.addEventListener('load', (event) => {
if (event.target.status !== 200) {
const e = '<p>Error ' + event.target.status + ': ' + event.target.statusText + ' (sorry)</p>';
document.getElementById(rssList).insertAdjacentHTML('beforeend', e);
return;
}
const result = event.target.responseText;
let data = [];
result.split('<item>').forEach(element => {
const postTitle = element.split('<title>')[1].split('</title>')[0];
const postLink = element.split('<link>')[1].split('</link>')[0];
var postDate = undefined; // item 0 (blog link/title) has no pubDate
if (element.includes('<pubDate>')) {
var postDate = element.split('<pubDate>')[1].split('</pubDate>')[0];
};
let post = {};
post.postTitle = postTitle;
post.postLink = postLink;
post.postDate = postDate;
data.push(post);
});
var d = document.getElementById(rssList);
var i;
for (i = 1; i < 4; i++) {
var t = data[i].postDate; // MMM DD, YYYY
var t = '<div class="date">' + t.substring(8, 11) + ' ' + t.substring(5, 7) + ', ' + t.substring(12, 16) + '</div>';
var s = '<li>' + t + '<a target="_blank" href="' + data[i].postLink + '">' + data[i].postTitle + '</a></li>';
d.insertAdjacentHTML('beforeend', s);
}
});
request.send();
}
.feed ul {
width: 95%;
list-style: none;
margin: 0;
color: #3E3E3E;
}
.feed li {
padding: 1em 0;
clear: both;
}
.feed .date {
font-family: "Inconsolata", monospace;
float: left;
line-height: 150%;
width: 17%;
color: #999;
margin-right: 1em;
}
.feed a {
line-height: 150%;
width: 80%;
float: right;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment