Home > Web Front-end > JS Tutorial > body text

What is onbeforeunload? how to use?

不言
Release: 2018-10-26 15:41:53
forward
3071 people have browsed it

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
Copy after login

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>
Copy after login

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>
Copy after login

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;
    }
  }
Copy after login


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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!