![](/img/trans.png)
[英]How to add event listeners to create-react-app default sw.js file
[英]How do I change the scope of the service worker sw.js
我正在使用react / redux和express通過HTTPS連接提供服務器端呈現的應用程序。
位於/ build / assets文件夾中的sw.js文件中的服務工作者代碼是
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/assets/sw.js', { scope: '/' }).then((registration) => {
console.log('SW registered: ', registration);
}).catch((registrationError) => {
console.log('SW registration failed: ', registrationError);
});
});
}
assets文件夾是為我的應用程序提供的,但我想將服務工作者的范圍更改為root即/
。
所以在express中我添加自定義標頭如下:
res.setHeader('Service-Worker-Allowed', '/');
但我仍然收到以下錯誤:
The path of the provided scope ('/') is not under the max scope allowed ('/assets/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.
我是否在正確的位置添加標題? 我需要做更多的事情嗎?
如果需要更多信息,請發表評論。
任何有關該解決方案的幫助將受到高度贊賞。
在Jeff Posnick的評論之后我找到了解決方案。 我發布這個以防其他人卡住並需要一些幫助。
必須在服務工作文件上專門設置標頭而不是根文檔。
要在快遞中這樣做:
const options = {
setHeaders: function (res, path, stat) {
res.set('Service-Worker-Allowed', '/');
},
};
app.use(express.static(path.join(process.cwd(), './build/public'), options));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.