我試圖在測試頁面中實現Service Worker
。我的最終目標是脫機運行的應用程序。文件夾結構如下瞭解服務人員範圍
/myApp
...
/static
/mod
/practice
service-worker.js
worker-directives.js
foopage.js
/templates
/practice
foopage.html
我註冊,如下圖所示(內service-worker.js
)服務工作者:
navigator.serviceWorker.register('../static/mod/practice/service-worker.js').then(function(reg) {
console.log('Registration succeeded. Scope is ' + reg.scope);
...
}
並在控制檯中我看到
Registration succeeded. Scope is https://example.com/static/mod/practice/
如果我頁面位於https://example.com/practice/foopage
,我是否需要確保我的service worker
範圍是https://example.com/practice/foopage
?
如果我嘗試在register
函數調用像
navigator.serviceWorker.register('../static/mod/practice/service-worker.js', { scope: '/practice/foopage/' }).then(function(reg) {
...
}
定義的範圍,我得到了錯誤
Registration failed with SecurityError: Failed to register a ServiceWorker: The path of the provided scope ('/practice/foopage/') is not under the max scope allowed ('/static/mod/practice/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.
的問題是:究竟是什麼範圍指什麼? service worker
最終將控制哪些網址的集合?我需要在其他地方移動service-workers.js
嗎?如果是這樣,在哪裏?
我沒想到在根目錄下的'js'文件是有史以來東西會做。但是,隨着新概念的出現,我猜想新的範例 –
我認爲這主要是出於安全原因。例如,如果你只能訪問'/ static',但不能訪問根目錄('/'),你的服務工作者就不應該攔截到根的請求。 – nils
這只是部分正確 - 範圍決定哪些頁面由服務工作人員控制。一旦頁面由服務工作人員控制,所有* HTTP請求源於該頁面,而不管請求URL如何,都將觸發服務工作人員的「獲取」事件。因此,如果受控頁面爲'https:// thirdpartyapi.com/api/test'發出AJAX請求,則您的服務工作人員將有機會截取該請求。 –