【问题标题】:Service worker not creating networkFirst CacheService Worker 未创建 networkFirst Cache
【发布时间】:2019-05-13 19:53:44
【问题描述】:

我的服务人员:

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);
 });

precache 缓存有效,但 onlineResources 缓存从未创建。

看看我的文件结构:

所以我认为范围不是问题,即使我在 Chrome 开发工具上看不到我的 service worker 中的客户端。

最后是我的 app.js 文件:

    //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 插入 newsAPI 并将 JSON 输出到页面 HTML。

【问题讨论】:

  • 如果我使用普通的 JS 非 Workbox 语法,我可以在页面刷新时获得动态缓存。我还注意到当我 console.log SW 的位置时,我得到了这个响应:@ 987654325@http 协议会不会导致不安全的问题?
  • 使用 vanilla Js NetworkFirst 方法我还在服务工作者开发工具中获得客户端

标签: caching service-worker browser-cache progressive-web-apps workbox


【解决方案1】:

当您注册路由时,您似乎正在尝试使用正则表达式作为字符串。我认为它实际上是将路线解释为包含.* 的字符串。而是尝试使用正则表达式 /^https:\/\/newsapi\.org/,每个 docs 将从 url 的开头匹配。

【讨论】:

  • Uncaught SyntaxError: 无效的正则表达式://^newsapi.org(.*)/: Unmatched ')'
  • @ChrisCullen 你试过我的吗?您的正则表达式只会匹配以newsapi[any non-line break character]org[zero or more of any non-line break character] 开头的网址。如果你点击 https,它就不会匹配。
  • 是的,那是你的代码的结果......我相信我要去的 API 是 https
  • @ChrisCullen 使用workbox.routing.registerRoute(/^https:\/\/newsapi\.org/, args =&gt; { return onlineResources.handle(args); });workbox.routing.registerRoute( /^newsapi.org(.*)/, args =&gt; { return onlineResources.handle(args); }); 的结果是unmatched ')' 错误???不知道怎么会这样。。。???它没有任何括号,怎么会这样出错?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2019-02-16
  • 1970-01-01
  • 2018-11-30
  • 2020-04-14
  • 1970-01-01
相关资源
最近更新 更多