Lew*_*wis 8 javascript url service-worker
如何获取在ServiceWorker范围内注册ServiceWorker的页面的URL?
console.log(window.location.pathname); // /user
navigator.serviceWorker.register('/app/sw.js',{scope : '/user'}).then(function(){
console.log('Service Worker initialised');
}).catch(function(er){
console.log('er.message);
});
Run Code Online (Sandbox Code Playgroud)
console.log(self.location.pathname); // /sw.js
// How can I get the `/user` URI?
Run Code Online (Sandbox Code Playgroud)
Jef*_*ick 17
在服务工作者中,self.registration.scope将为您提供相关的范围.这在Chrome 42+(刚刚成为稳定版本)中可用,因此使用起来应该是安全的.
我想你也可能会询问如何获得服务工作者控制的所有活动页面的引用?如果是这种情况,答案是使用self.clients.matchAll()(也可在Chrome 42+中使用),它将返回一个(可能为空)WindowClient对象数组,对应于每个打开的受控页面.使用相应的URL WindowClient公开url属性.