How to restrict the folders that lie under the scope while registering service workers.
I have a folder structure like this.
-root
-folder1
-subfolder1
-subfolder2
-subfolder3
-file.js
-file2.js
-css1.css
-css2.css
-serviceworker.js
According to my understanding:
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('serviceworker.js',)
.then(function(reg) {
console.log('Registration succeeded', reg);
})
Here the serviceworker.js file is under the folder1 folder, which means that all the files and sub folders inside folder1 are under the scope.
What I want: Is there any way to restrict the files and folders that come under the scope of service workers say subfolder1 and file.js.
Thanks in advance
You can't specifically restrict a service worker's scope to only apply to one sub-path but not another when they both share the same parent path.
The most straightforward approach would be to explicitly check the URL in your fetch
handler and only call event.respondWith()
when the URL matches one of the paths/files you care about. If you don't call event.respondWith()
, the fetch
handler will basically be a no-op, and the service worker won't be involved in responding to the request.
Eg:
self.addEventListener('fetch', event => {
if (event.request.url.includes('subfolder1')) {
event.respondWith(/* your caching/network logic */);
}
// By not calling event.respondWith() for certain requests,
// the service worker will effectively be a no-op.
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.