Skip to content

Instantly share code, notes, and snippets.

Last active September 19, 2018 01:59
Show Gist options
  • Save chrisjonesio/5cc569498808a5302f8462672e919230 to your computer and use it in GitHub Desktop.
Save chrisjonesio/5cc569498808a5302f8462672e919230 to your computer and use it in GitHub Desktop.
A quick demo showing how to grab the title and descritpion of cached articles on an offline page displayed from a service worker
// first open the articles cache
// this cache is specified in the service worker where the
// offline handling code is kept'articles')
.then(articlesCache => {
.then(keys => {
// loop over each article from the cache
keys.forEach(request => {
let markup = '';
let articleTitle = '';
let articleDescription = '';
// fetch the article, this will fail (we're offline)
// and return the cached article
.then(response => {
let contentType = response.headers.get('content-type');
if (contentType.includes('text/html')) {
return response.text();
.then(text => {
// fire up a new DOMParser, we'll use it to parse the returned HTML article
const parser = new DOMParser();
const htmlDocument = parser.parseFromString(text, "text/html");
// heyyyooo, use the DOM to get the title of the article
articleTitle = htmlDocument.documentElement.querySelector("title").innerText;
// here one could maybe strip out stuff from the title string one
// doesn't want to display
// we can also get the article description from the document,
// it is after all, THE ARTICLE DOCUMENT
articleDescription = htmlDocument.documentElement.querySelector('meta[name="description"]').getAttribute('content');
// one could pull from the parsed HTML document anything they wish
// at this point. got images cached? get one of 'em to display
// with the title and description.
// now it's time to output the title and description
// the list item will go into a <ul> in the offline template
const articleListItem = document.createElement("li");
const articleListItemLink = document.createElement("a");
// just checking if the article title is blank (it shouldn't be)
// and if it is just jam the link into the list of offline articles
if (articleTitle == '') {
articleListItemLink.href = request.url;
articleListItemLink.innerText = request.url;
else {
// cool, we have a title, so let's make a slightly more attractive
// article/description block
// one could make whatever markup/layout one wanted here
articleListItemLink.href = request.url;
articleListItemLink.innerText = articleTitle;
const articleListItemBreak1 = document.createElement("br");
const articleListItemDescription = document.createTextNode(articleDescription);
// now append the offline article to the list in the offline page template
.catch( () => {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment