简体   繁体   中英

How to close modal dialog from parent window?

How can I close modal dialog(s) from main page after some time, or when session expires, using JavaScript or jQuery?

Dialog is opened using the following code :

var result = window.showModalDialog("test.aspx" ... );

Dialog must be closed when counter expires like this:

 function Discount() {
     leftSeconds = leftSeconds - 1;
     try { document.getElementById('tbLeft').value = leftSeconds; } catch (ex) { }
     if (leftSeconds <= 5) {
          clearTimeout(t);
          // code for closing modal dialog(s)

     } else {
          t = setTimeout("Discount()", 1000);
     }
 }

Modal dialog can be closed from himself, but it's not solution in my case.

While the modal dialog is open, javascript execution on the main page is stopped, because it is waiting for a return value (even though you may not want to return one, or do anything with what it returns).

You can check this with this little example. When you click the button, the page opens, and the timer stops updating. When you close the page, execution is resumed:

<!DOCTYPE html>
<html>
<head>
    <script>
        var t = 0;
        function count() {
            document.getElementById('div').innerHTML = ++t;
        }
        var timer = setInterval(count, 1000);
    </script>
</head>
<body>
    <div id='div'></div>
    <button onclick="window.showModalDialog('http://www.google.es');">Open window</button>
</body>
</html>

So, if you want to close the window automatically, you need to do it from the new document itself. My advice? Implement your timer in the window.load event of your modal page, so it can close itself after the desired time.

window.onload = function() {
    setTimeout(function() { window.close(); }, 60000); //close window after 1 minute.
};

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