Skip to content

Instantly share code, notes, and snippets.

@flexchar
Last active June 1, 2019 11:50
Show Gist options
  • Save flexchar/df44f0aaf1d57283a3d923af705806e6 to your computer and use it in GitHub Desktop.
Save flexchar/df44f0aaf1d57283a3d923af705806e6 to your computer and use it in GitHub Desktop.
Instagram feed component
window.addEventListener(
'DOMContentLoaded',
(): void => {
const container: HTMLDivElement = document.querySelector(
'[data-instagram]'
);
if (!container) {
console.log('No Instagram container found');
return;
}
if (false === 'fetch' in window) {
console.log(`This browser doesn't support fetch API`);
return;
}
const user_name: string = container.dataset.instagram;
// console.log(`Fetching Instagram feed for ${user_name}...`);
fetch(`https://www.instagram.com/${user_name}/`, {
method: 'GET'
})
/**
* Returns scraped Instagram HTML view
*
*/
.then((res: Response) => {
return res.text();
})
/**
* Returns extracted and cleaned array of images
*
*/
.then((source: string) => {
// Extract 'window._sharedData' object
source = source.split(
'<script type="text/javascript">window._sharedData = '
)[1];
source = source.split(';</script>')[0];
// Turn into 'real' object
const data = JSON.parse(source);
// Select images object
return data.entry_data.ProfilePage[0].graphql.user
.edge_owner_to_timeline_media.edges;
})
/**
* Pushes images into container on website,
* Container is identified by
* data-instagram attribute
*
*/
.then((images: Array<any>) => {
if (!images) return;
// Only take first 5 images
images = images.slice(0, 5);
// Push images into container
images.forEach(image => {
// Extract image thumbnail url
// Index defines different sizes
// 0 - 150px, 1 - 240px, 2 - 320px, 3 - 480px, 4 - 640px
const src = image.node.thumbnail_resources[1].src;
let img = document.createElement('img');
img.src = src;
container.appendChild(img);
});
})
.catch(err => {
console.log('failed to fetch', err);
});
},
{ passive: true }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment