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

fre*_*ent 1 javascript service-worker

我无法绕过ServiceWorker 的Clients.claim API.根据我的理解(这里这里),我可以调用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() {...}
      );
    })
  );
});
Run Code Online (Sandbox Code Playgroud)

以上运行但我最终不得不刷新并Illegal invocation在Chrome ServiceWorker内部发现错误.如果我clients.claimwaitUntil处理程序中删除并取消注释前一个,我没有错误,但我仍然需要刷新.调试器显示:

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":""}
Run Code Online (Sandbox Code Playgroud)

刷新是这样触发的:

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.");
    }
  }); 
Run Code Online (Sandbox Code Playgroud)

问题:
如何正确防止必须刷新页面以使用激活ServiceWorker claim?我发现提到的所有链接都没有明确检查,controller但我认为如果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();
    })
  );
});
Run Code Online (Sandbox Code Playgroud)

触发脚本:

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;
      });
  });
Run Code Online (Sandbox Code Playgroud)

Umu*_*göz 5

首先,由于代码中存在拼写错误,您似乎得到了错误.请在底部查看有关它的说明.

此外,skipWaiting()没有都安装并激活新的与单个请求SW.但很自然地,你只会在重新加载后获得像css这样的静态资产.Clients.claim()

所以,即使配备skipWaiting()Clients.claim(),你需要两页重新加载,以查看更新的static内容,如新的HTML或样式;

页面加载#1

  • 发出请求sw.js,并且由于SW内容被更改, install因此触发事件.
  • activate事件也被触发,因为您self.skipWaiting()install处理程序中.
  • 因此,您的activate处理程序运行并且有您的self.clients.claim()呼叫.这将命令SW接管其前任控制下的所有客户的控制权.
  • 此时,缓存中的资产会更新,您的页面都将由新服务工作者控制.例如,服务工作者范围内的任何Ajax请求都将返回新缓存的响应.

页面加载#2

您的应用加载,并且您的SW通过像往常一样劫持请求来响应缓存.但现在缓存是最新的,用户可以完全使用新资产.

你得到的错误

Uncaught (in promise) TypeError: Illegal invocation错误必须是由于activate处理程序中缺少括号;

  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.
    })
  );
Run Code Online (Sandbox Code Playgroud)

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