简体   繁体   中英

How to run a Javascript code on closing the opened window?

I want to do something when I close the opened window (let's say just print hello world on console).

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible"
         content="IE=edge">
        <title>window</title>
        <meta name="viewport" 
        content="width=device-width, initial-scale=1">
    </head>
    <body>
        <button onclick="openwindow()">Show Window</button>


        <script>
            function openwindow(){
                window.open("https://www.google.com",'newwindow',
                'scrollbars=no,menubar=no,height=600,width=800,
                resizable=yes,toolbar=no,status=no');
            }
        </script>
    </body>
</html>

As you can see I have a button. When I click this button it opens another window and opens Google in it.

So when I close this new window I want to run some code without opening further dialog box. How can I achieve it?

The popup window does not have any close event that you can listen to but there is a closed property that is true when window gets closed. You can detect that event with the help of starting a timer and checking the closed property of the child window every second and clear the timer when the window gets closed. Something like this:

var windowPopup = window.open("https://www.google.com",'newwindow',
                'scrollbars=no,menubar=no,height=600,width=800'); 
var timer = setInterval(function() { 
    if(windowPopup.closed) {
        clearInterval(timer);
        alert('closed');
    }
}, 1000);


I dont know if I understand you correctlly, but I think you can easily use 'onbeforeunload()' event.

<body onbeforeunload="myFunction()">
</body>

function myFunction() {
    localStorage.setItem("dataSet", 'dataSet');
}


you can check the webStorage to see that it write the variable before the page is closed.
does that helps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM