也许你试着设置onerror
处理程序navigator.serviceWorker
容器这样的:
// no effect outside service worker script
navigator.serviceWorker.onerror = function() {...};
错误处理程序必须从服务工作者脚本内设置有self.onerror
(self
是一个特殊的变量/属性这里指的是ServiceWorkerGlobalScope
)。 onerror
回调仅提供一条错误消息。
// inside service worker script
self.onerror = function(message) {
console.log(message);
};
或者,你可以听服务人员的error
事件,其中包括包含错误的位置的ErrorEvent
:
// inside service worker script
self.addEventListener('error', function(e) {
console.log(e.filename, e.lineno, e.colno, e.message);
});
这里有一个demo。务必从DevTools>资源>服务工作者(左面板)删除服务工作者因为这将填补这些失败的服务工作者注册:
我已经验证了以下浏览器支持onerror
服务人员的实例中:
- 铬51(稳定)和53(金丝雀)
- 火狐47
- 歌剧38(稳定)和39(开发者)
UPDATE:
So when MDN describes the ServiceWorkerContainer
interface, that is referring to self
(ServiceWorkerGlobalScope
) and not navigator.serviceWorker
?
我认为这是只为onerror
属性为真(也许对其他事件有作为),我猜测该规范尚未更新,以反映商定的实施情况......
的服务人员工作组已决定从ServiceWorkerContainer
到服务工人实例移动onerror
,在GitHub的讨论(slightlyoff/ServiceWorker
#198):
kinu commented on Apr 2, 2014
sgtm2. For error reporting (onerror
stuff) we could probably do similar? E.g. moving .onerror
handler from container to SW object, so that doc can explicitly know which SW the error is coming from (though it may need to attach handlers to multiple SWs).
然后有后续评论在相关指示缺乏有用的为onerror
容器上的问题(slightlyoff/ServiceWorker
#104):
jakearchibald commented on Apr 3, 2014
Thinking about the use-cases (following from #198)…
navigator.serviceWorker.onerror
or navigator.serviceWorker.pending.onerror
(whichever it becomes) are not useful for logging errors back to the server, as errors can happen outside of the life of any page. onerror
inside the worker itself is best for that.
.pending.onerror
is useful if you're updating the UI in response to an update. So maybe it's better as a statechange
, although you'd need somewhere to put the error message.
That leaves errors that happen before the SW instance is created. AppCache has an error event that covers network-related update failures, and also parse failures. However, once again we'd lose any errors that happened outside the life of a page.
“*最初不确定*” - 你的意思是它确实有undefined'的'的值(这是原因能够),还是该财产根本不存在? – Bergi
@Bergi它有一个'undefined'的值,这让我觉得不寻常,因为window.onerror最初是'null'。编辑:我加倍检查,这也是属性不存在''onerror'navigator.serviceWorker // false' –