Chris Cullen
Chris Cullen

Reputation: 110

Service worker not creating networkFirst Cache

My Service Worker:

importScripts('https://storage.googleapis.com/workbox- 
cdn/releases/3.0.0/workbox-sw.js');

//Use Workbox Precache for our static Assets

workbox.precaching.precacheAndRoute([]);
console.log('this is my custom service worker');


//Create articles Cache from online resources
const onlineResources = workbox.strategies.networkFirst({
cacheName: 'articles-cache',
plugins: [
  new workbox.expiration.Plugin({
    maxEntries: 50,
    }),
   ],
  });


workbox.routing.registerRoute('https://newsapi.org/(.*)', args => {
return onlineResources.handle(args);
 });

The precache cache works but the onlineResources Cache is never created.

A look at my file structure:

enter image description here

So I don't think scope is an issue even though I cant see clients in my service worker on Chrome dev tools.

Lastly here is my app.js file:

    //main populates main tags in indexpage
const main  = document.querySelector('main');
//this populates the source dropdown menu with sources
const sourceSelector = document.querySelector('#sourceSelector');
//set default source so page loads this
const defaultSource = 'bbc-news';

//on window load call update news and when update
window.addEventListener('load', async e => {
    updateNews();
   await updateSources();
   sourceSelector.value = defaultSource;

   //when sourceSelector is changed update the news with the new source
   sourceSelector.addEventListener('change',e =>{
       updateNews(e.target.value);
   });



//checks for serviceWorker in browser
if('serviceWorker'in navigator){
    try{
        //if there is register it from a path
        navigator.serviceWorker.register('/sw.js');
        console.log('registered!');
        }  catch(error){
        console.log('no register!',error);
    }
}
});



async function updateNews(source= defaultSource){
//response awaits a fetch of the news API call
const res = await fetch(`https://newsapi.org/v2/top-headlines?sources=${source}&apiKey=82b0c1e5744542bdb8c02b61d6499d8f`);
const json = await res.json();

//fill the html with the retrieved json articles
main.innerHTML = json.articles.map(createArticle).join('\n');
}


//Update the news source
async function updateSources(){

    const res = await fetch(`https://newsapi.org/v2/sources?apiKey=82b0c1e5744542bdb8c02b61d6499d8f`);
    const json = await res.json();

    //Whatever source the sourceSelector picks gets mapped and we take the id of it - It is used with updateNews();
    sourceSelector.innerHTML = json.sources
    .map(src=>`<option value="${src.id}">${src.name}</option>`).join('\n');
    }







function createArticle(article){
    return `     <div class="article">
        <a href="${article.url}">
        <h2>${article.title}</h2>
        <img src="${article.urlToImage}">
        <p>${article.description}</p>
        </a>
        </div>
    `;
}

App.js plugs into newsAPI and outputs the JSON to the pages HTML.

Upvotes: 1

Views: 437

Answers (1)

James South
James South

Reputation: 604

When you register the route you seem to be trying to use a regex as a string. I think it is literally interpreting the route as a string that includes .*. Instead try the regex /^https:\/\/newsapi\.org/ which per the docs will match from the beginning of the url.

Upvotes: 0

Related Questions