发布时间:2025-12-11 01:55:59 浏览次数:1
onbeforeunload是一个事件,当页面将要被卸载(更新)的时候会被触发。
卸载(更新)讲的就是unload事件,当页面关闭后,会触发。
window.onbeforeunload = funcRef
funcRef指的是一个方法,也就是一个函数引用。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>test</title></head><body onbeforeunload="return test()"> </body><script type="text/javascript"> function test(){ return "你确定要离开吗"; }</script></html><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>test</title></head><body> </body><script type="text/javascript">window.onbeforeunload=function(){ return "你确定要离开吗";} </script></html>一般在项目中直接使用window或者body会导致整个项目的页面的刷新关闭事件都被拦截。
想在某个页面中使用这个拦截的大体思路是在进入这个页面的时候挂载该事件,跳转页面的时候将挂载的事件取消。
例如在react中:
componentDidMount() { window.onbeforeunload = function() { return "真的离开?"; }; }componentWillUnmount(){ window.onbeforeunload = function() { return null; } }