Home  >  Article  >  Web Front-end  >  What is onbeforeunload? how to use?

What is onbeforeunload? how to use?

不言
不言forward
2018-10-26 15:41:533150browse

This article brings you what is onbeforeunload? how to use? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is onbeforeunload?

  • onbeforeunload is an event that will be triggered when the page is about to be unloaded (updated).

  • Uninstall (update) is about the unload event, which will be triggered when the page is closed.

2. Grammar rules

window.onbeforeunload = funcRef

funcRef refers to a method, which is a function reference.

3. How to use this thing

3.1 In HTML, mount it directly to the body

<!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>

3.2 In js, use the window.onbeforeunload binding method

<!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>

3.3 Use in a single page:

Generally, using window or body directly in a project will cause the refresh and close events of the entire project page to be intercepted.
The general idea of ​​using this interception in a certain page is to mount the event when entering the page, and cancel the mounted event when jumping to the page.
For example in react:

componentDidMount() {
    window.onbeforeunload = function()
    {
      return "真的离开?";
    };
  }
componentWillUnmount(){
    window.onbeforeunload = function()
    {
      return null;
    }
  }


The above is the detailed content of What is onbeforeunload? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete