也許你試着設置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' –