use*_*439 6 reactjs service-worker create-react-app
我希望用户能够在有新服务人员可用时等待现场更新?当有新的更新可用时,我已经能够显示一个弹出窗口,但是我想添加一个按钮来当场强制更新。我知道可以通过调用skipWaiting来实现,但是不确定如何使用Create React App来实现它。有谁能做到这一点?希望能有所帮助。谢谢!
use*_*640 34
CRAbuild\service-worker.js文件现在(v3 plus)包含处理代码skipWaiting:
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
Run Code Online (Sandbox Code Playgroud)
serviceWorker.js被调用的注册函数文件index.js现在接受一个配置参数:
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
Run Code Online (Sandbox Code Playgroud)
这将跳过等待,然后在应用更新后刷新页面。
在serviceWorker.js文件中可以找到此代码
if (config && config.onUpdate) {
config.onUpdate(registration);
}
Run Code Online (Sandbox Code Playgroud)
因此实现config.onUpdate功能
创建文件swConfig.js
export default {
onUpdate: registration => {
registration.unregister().then(() => {
window.location.reload()
})
},
onSuccess: registration => {
console.info('service worker on success state')
console.log(registration)
},
}
Run Code Online (Sandbox Code Playgroud)
在index.js处将实现函数发送给serviceWorker
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import swConfig from './swConfig'
ReactDOM.render(<App />,
document.getElementById('root'));
serviceWorker.register(swConfig);
Run Code Online (Sandbox Code Playgroud)
查看此仓库 https://github.com/wgod58/create_react_app_pwaupdate
我使用了一个名为https://github.com/bbhlondon/cra-append-sw的包附加以下代码来调用触发器skipWaiting:
self.addEventListener('message', event => {
if (event.data === 'skipWaiting') {
self.skipWaiting();
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1863 次 |
| 最近记录: |