编程语言
首页 > 编程语言> > javascript-初始化ServiceWorker以防止必须重新加载页面时如何声明客户端?

javascript-初始化ServiceWorker以防止必须重新加载页面时如何声明客户端?

作者:互联网

我无法将自己的头缠在ServiceWorker的Clients.claim API上.根据我的理解(herehere),我可以在service worker激活事件上调用claim(),以防止必须刷新页面来初始化ServiceWorker.我无法使其正常运行,并且总是不得不刷新.这是我的代码:

在服务人员内部:

self.addEventListener('install', function (event) {

  self.skipWaiting();

  event.waitUntil(caches.open(CURRENT_CACHE_DICT.prefetch)
    .then(function(cache) {
      var cachePromises = PREFETCH_URL_LIST.map(function(prefetch_url) {
        var url = new URL(prefetch_url, location.href),
          request = new Request(url, {mode: 'no-cors'});

        return fetch(request).then(function(response) {
          if (response.status >= 400) {
            throw new Error('request for ' + prefetch_url +
              ' failed with status ' + response.statusText);
          }
          return cache.put(prefetch_url, response);
        }).catch(function(error) {
          console.error('Not caching ' + prefetch_url + ' due to ' + error);
        });
      });

      return Promise.all(cachePromises).then(function() {
        console.log('Pre-fetching complete.');
      });
    }).catch(function(error) {
      console.error('Pre-fetching failed:', error);
    })
  );
});

self.addEventListener('activate', function (event) {

  // claim the scope immediately
  // XXX does not work?
  //self.clients.claim();

  event.waitUntil(self.clients.claim()
    .then(caches.keys)
    .then(function(cache_name_list) {
      return Promise.all(
        cache_name_list.map(function() {...}
      );
    })
  );
});

上面的程序可以运行,但是我最终不得不刷新,并在Chrome ServiceWorker内部发现了非法调用错误.如果我从waitUntil处理程序中删除clients.claim并取消对前一个的注释,则不会出现任何错误,但仍然需要刷新.调试器显示:

Console: {"lineNumber":128,"message":"Pre-fetching complete.","message_level":1,"sourceIdentifier":3,"sourceURL":""}
Console: {"lineNumber":0,"message":"Uncaught (in promise) TypeError: Illegal invocation","message_level":3,"sourceIdentifier":1,"sourceURL":""}

刷新触发如下:

function waitForInstallation(registration) {
    return new RSVP.Promise(function(resolve, reject) {
        if (registration.installing) {
      registration.installing.addEventListener('statechange', function(e) {
        if (e.target.state == 'installed') {
          resolve();
        } else if (e.target.state == 'redundant') {
          reject(e);
        }
      });
    } else {
      resolve();
    }
  });
}

// refreshing should not be necessary if scope is claimed on activate
function claimScope(installation) {
  return new RSVP.Promise(function (resolve, reject) {
    if (navigator.serviceWorker.controller) {
      resolve();
    } else {
      reject(new Error("Please refresh to initialize serviceworker."));
    }
  });
}

rJS(window)
  .declareMethod('render', function (my_option_dict) {
    var gadget = this;

    if ('serviceWorker' in navigator) {
      return new RSVP.Queue()
        .push(function () {
          return navigator.serviceWorker.register(
            my_option_dict.serviceworker_url,
            {scope: my_option_dict.scope}
          );
        })
        .push(function (registration) {
          return waitForInstallation(registration);
        })
        .push(function (installation) {
          return claimScope(installation);
        })
        .push(null, function (my_error) {
          console.log(my_error);
          throw my_error;
        });
    } else {
      throw new Error("Browser does not support serviceworker.");
    }
  }); 

题:
如何正确防止必须使用版权声明刷新页面才能激活ServiceWorker?我发现没有任何链接提到必须显式检查控制器,但是我假设ServiceWorker如果处于活动状态,它将可以访问控制器.

感谢您删除一些信息.

编辑:
在下面的帮助下找到了答案.这使它对我有用:

// runs while an existing worker runs or nothing controls the page (update here)
self.addEventListener('install', function (event) {

  event.waitUntil(caches.open(CURRENT_CACHE_DICT.dictionary)
    .then(function(cache) {
      var cache_promise_list = DICTIONARY_URL_LIST.map(function(prefetch_url) {...});

      return Promise.all(cache_promise_list).then(function() {
        console.log('Pre-fetching complete.');
      });
    })
    .then(function () {

      // force waiting worker to become active worker (claim)
      self.skipWaiting();

    }).catch(function(error) {
      console.error('Pre-fetching failed:', error);
    })
  );
});

// runs active page, changes here (like deleting old cache) breaks page
self.addEventListener('activate', function (event) {

  event.waitUntil(caches.keys()
    .then(function(cache_name_list) {
      return Promise.all(
        cache_name_list.map(function(cache_name) { ... })  
      );
    })
    .then(function () {
      return self.clients.claim();
    })
  );
});

触发脚本:

var SW = navigator.serviceWorker;    

function installServiceWorker(my_option_dict) {
  return new RSVP.Queue()
    .push(function () {
      return SW.getRegistration();
    })
    .push(function (is_registered_worker) {

      // XXX What if this isn't mine?
      if (!is_registered_worker) {
        return SW.register(
          my_option_dict.serviceworker_url, {
            "scope": my_option_dict.scope
          }
        );   
      }
      return is_registered_worker;
    });
}

function waitForInstallation(registration) {
  return new RSVP.Promise(function(resolve, reject) {
    if (registration.installing) {
      // If the current registration represents the "installing" service
      // worker, then wait until the installation step completes (during
      // which any defined resources are pre-fetched) to continue.
      registration.installing.addEventListener('statechange', function(e) {
        if (e.target.state == 'installed') {
          resolve(registration);
        } else if (e.target.state == 'redundant') {
          reject(e);
        }
      });
    } else {
      // Otherwise, if this isn't the "installing" service worker, then
      // installation must have beencompleted during a previous visit to this
      // page, and the any resources will already have benn pre-fetched So
      // we can proceed right away.
      resolve(registration);
    }
  });
}

// refreshing should not be necessary if scope is claimed on activate
function claimScope(registration) {
  return new RSVP.Promise(function (resolve, reject) {
    if (registration.active.state === 'activated') {
      resolve();
    } else {
      reject(new Error("Please refresh to initialize serviceworker."));
    }
  });
}

rJS(window)

  .ready(function (my_gadget) {
    my_gadget.property_dict = {};
  })

  .declareMethod('render', function (my_option_dict) {
    var gadget = this;

    if (!SW) {
      throw new Error("Browser does not support serviceworker.");
    }

    return new RSVP.Queue()
      .push(function () {
        return installServiceWorker(my_option_dict),
      })
      .push(function (my_promise) {
        return waitForInstallation(my_promise);
      })
      .push(function (my_installation) {
        return claimScope(my_installation);
      })
      .push(function () {
        return gadget;
      })
      .push(null, function (my_error) {
        console.log(my_error);
        throw my_error;
      });
  });

解决方法:

首先,由于代码中的错字,您似乎正在得到错误.请参阅底部的注释.

此外,skipWaiting()Clients.claim()都可以通过一个请求安装和激活新的软件.但是很自然地,您只会在重新加载后获得诸如CSS之类的静态资产.

因此,即使配备了skipWaiting()和Clients.claim(),您也需要重新加载两次页面才能看到更新的静态内容,例如新的html或样式;

页面加载#1

>发出对sw.js的请求,并在其上触发since SW contents is changed安装事件.
>因为您在安装处理程序中有self.skipWaiting(),所以还会触发Activate事件.
>因此,您的激活处理程序运行,并且您进行了self.clients.claim()调用.它将命令SW接管所有在其前身控制下的客户端的控制.
>此时,缓存中的资产已更新,并且您的页面全部由新服务工作者控制.例如,服务工作者范围内的任何Ajax请求都将返回新缓存的响应.

页面加载#2

您的应用加载完毕,您的软件通过照常劫持请求来响应缓存.但是现在,缓存是最新的,用户可以将应用程序与新资产完全一起使用.

您收到的错误

未捕获(承诺)TypeError:非法调用错误必须归因于激活处理程序中缺少括号;

  event.waitUntil(self.clients.claim()
    .then(caches.keys)
    .then(function(cache_name_list) {
      return Promise.all(
        cache_name_list.map(function() {...}
      ); <-- Here is our very lonely single parenthesis.
    })
  );

如果您修复此错误,该错误应消失.

标签:javascript,service-worker
来源: https://codeday.me/bug/20191012/1900901.html