Reddit GET Info API Embed Demo
by joshuatz
HTML
<!-- UI -->
<div class="top">
<input type="url" id="redditUrlInput" placeholder="https://www.reddit.com/r/food/comments/60jxzo/homemade_breakfast_sugar_cookies/" />
<button onclick="auto()">Generate</button>
<button onclick="demo()">Demo</button>
</div>
<div id="embedTarget">
</div>
CSS
.top {
width: 100%;
margin-bottom: 10px;
}
#redditUrlInput {
width: 50%;
display: inline-block;
max-width: 400px;
margin-right: 10px;
margin-bottom: 10px;
}
button {
width: calc(20% - 20px);
min-width: 80px;
display: inline-block;
}
.reddit-embed {
width: 350px;
height: 200px;
border: 4px solid black;
box-shadow: 5px 5px 5px 0px #000000;
}
.poster {
color: grey;
}
.title, .title a {
color: black !important;
font-weight: bolder;
text-align: center;
padding: 8px;
}
.reddit-embed {
padding-left: 4px;
}
.body-left {
width: 80%;
}
.body-right {
width: 25%;
margin-left: 75%;
padding-top: 10px;
}
.body-left {
float: left;
}
.imageWrapper {
width: 100%;
text-align: center;
padding: 6px;
}
.imageWrapper img {
height: 131px;
width: auto;
border-radius: 10px;
}
JavaScript
function demo() {
document.getElementById('redditUrlInput').value = 'https://www.reddit.com/r/food/comments/60jxzo/homemade_breakfast_sugar_cookies/';
auto();
}
function auto() {
const url = document.getElementById('redditUrlInput').value;
generateEmbed(url);
}
function generateEmbed(url) {
const regPatt = /reddit\.com\/r\/[^\/]+\/comments\/([^\/]{6,})\//;
if (regPatt.test(url)) {
const fullname = 't3_' + regPatt.exec(url)[1];
fetch(`https://api.reddit.com/api/info/?id=${fullname}`)
.then(res => res.json())
.then(json => generateEmbedFromRedditJson(json));
}
else {
alert('Please enter a valid reddit post URL.')
}
}
/**
* Parse and generate embed from API response
* @param {Object} redditJson
*/
function generateEmbedFromRedditJson(redditJson) {
console.log(redditJson);
const selfData = redditJson.data.children[0].data;
const { author, permalink, score, thumbnail, title, url } = selfData;
const subreddit = selfData.subreddit_name_prefixed;
const html = `
<div class="reddit-embed">
<div class="header">
<div class="poster">Posted by ${author}</div>
<div class="title"><a href="${permalink}" target="_blank">${title}</a></div>
</div>
<div class="body-left">
<div class="imageWrapper">
<img src="${thumbnail}" />
</div>
</div>
<div class="body-right">
<div class="score">${String.fromCharCode(0x2195)} = ${score}</div>
</div>
</div>
`;
document.getElementById('embedTarget').innerHTML = html;
}