How jQuery can prevent reopening a new window?

2019-09-16 16:37发布

问题:

I have the code below to open a new window whenever user presses F2 key.

$(document).bind('keyup', function(e){
    if(e.which==113) {
        window.open('newPage.htm','_blank','','false');
    }
});

Now, I want to prevent user to open a new window while the previous one is still opened. How can I dot it ?

回答1:

var opened = null;
$(document).bind('keyup', function(e){
    if (e.which == 113 && (!opened || !opened.window))
        opened = window.open('newPage.htm','_blank','','false');
​});​


回答2:

Give your window a name like

var mywindow = window.open("foo.html","windowName");

Then you can check if window is closed by doing

if (mywindow.closed) { ... }


回答3:

You can try this ..

    var windowOpened=false;

    $(document).bind('keyup', function(e){
        if(e.which==113 && !windowOpened) {
            window.open('newPage.htm','_blank','','false');
            windowOpened=true;
        }
    });




   In the newPage.htm add code to make windowOpened=false when u close that window.


< html> 
< head>
< title>newPage.htm< /title>
<script>
function setFalse()
{
  opener.windowOpened = false;
  self.close();
  return false;
}
</script>
< /head>
< body onbeforeunload="setFalse()">
< /body> 
< /html> 


回答4:

When the windows is closed, what happens with window.document ? Does it become null , maybe you can check it by null.

var popupWindow;

$(document).bind('keyup', function(e){
    if(e.which==113 && (!popupWindow || !popupWindow.document)) {
        popupWindow = window.open('newPage.htm','_blank','','false');
    }
});