[英]How do I configure webpack-dev-server to turn off “beforeunload” events on the browser before reload?
My form pages have a beforeunload
event/function set on the window to warn the user to save their changes before moving on to a different page or refreshing.我的表单页面在 window 上设置了
beforeunload
事件/功能,以警告用户在转到其他页面或刷新之前保存更改。 It works great, and looks something like this:它工作得很好,看起来像这样:
$(window).on("beforeunload", myCustomWindowBeforeUnloadFunction);
The problem is when running in development, every time I change a file in my IDE, Webpack Dev Server attempts to auto-reload the page.问题是在开发中运行时,每次我更改 IDE、Webpack 中的文件时,开发服务器都会尝试自动重新加载页面。 I want to turn off this
beforeunload
event so I don't keep getting nagged with this alert in Chrome:我想关闭这个
beforeunload
事件,这样我就不会在 Chrome 中一直被这个警报所困扰:
Are you sure you want to leave the page? Data you have entered may not be saved.
Is there a way I can run a custom function in the browser before Webpack Dev Server attempts to reload the page?有没有办法在 Webpack 开发服务器尝试重新加载页面之前在浏览器中运行自定义 function?
Maybe something like this:也许是这样的:
if (process.env.DEV) {
window.addEventListener('message', ({ data: { type } }) => {
if (type === 'webpackInvalid') {
$(window).off('beforeunload');
} else if (type === 'INIT_INSTANCE') {
$(window).on('beforeunload', myCustomWindowBeforeUnloadFunction);
}
});
}
I've added process.env.DEV
with EnvironmentPlugin
to make sure that code doesn't make it to production.我添加了带有
EnvironmentPlugin
的process.env.DEV
以确保代码不会进入生产环境。 You could also use process.env.NODE_ENV === 'development'
, which works without adding EnvironmentPlugin
, as Webpack adds that automatically .您还可以使用
process.env.NODE_ENV === 'development'
,它无需添加EnvironmentPlugin
即可工作,因为Webpack 会自动添加。
Or, using HMR's addStatusHandler
function :或者,使用HMR 的
addStatusHandler
function :
if (process.env.DEV && module.hot) {
module.hot.accept();
module.hot.addStatusHandler((status) => {
if (status === 'prepare') {
$(window).off('beforeunload');
} else if (/apply|abort|fail/.test(status)) {
$(window).on('beforeunload', myCustomWindowBeforeUnloadFunction);
}
});
}
Note module.hot
will be there if you are using HotModuleReplacementPlugin
, no need to import that, as explained here :注意
module.hot
如果您使用的是HotModuleReplacementPlugin
,则无需导入,如下所述:
If Hot Module Replacement has been enabled via the
HotModuleReplacementPlugin
, its interface will be exposed under themodule.hot
property .如果通过
HotModuleReplacementPlugin
启用了热模块替换,则其接口将在module.hot
属性下公开。 Typically, users will check to see if the interface is accessible, then begin working with it.通常,用户会检查界面是否可访问,然后开始使用它。
Also, maybe instead of checking for apply
, abort
or fail
in the second condition, you could useidle
.此外,也许不是在第二种情况下检查
apply
、 abort
或fail
,您可以使用idle
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.