1
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
    <script>
        var win;
        $(document).on('click', '#okGoogle', function (event) {
            event.preventDefault();
            url = "http://www.google.com/";
            if (!win) {
                win = window.open(url, '_blank');
            }
            else {
                win.focus();
            }
        });
    </script>
</head>
<body>
    <button id="okGoogle">Ok Google</button>
</body>
</html>

This code works fine. But when newly opened window is closed, code does not open it again. Any suggestions?

Abhijeet
  • 13,562
  • 26
  • 94
  • 175

1 Answers1

2

You just need to check if the window has been closed, via its closed property.

if (!win || win.closed) {
    win = window.open(url, '_blank');
}

See the working fiddle here https://jsfiddle.net/c7q54ewt/

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Sergey Mell
  • 7,780
  • 1
  • 26
  • 50
  • Thanks, but Chrome only solution. Does not work on IE11 or Edge. – Abhijeet Jun 13 '17 at 10:52
  • 1
    @Abhijeet: Well, it also works on Firefox (Firefox doesn't like the `focus` call, however). I can verify that this doesn't work on IE11 (the return value of `window.open` is `null` so `win` is always falsy), which is unfortunate. I don't have Edge handy. I think this is as close as you're going to get without refreshing Google every time instead of just focussing the window without also refreshing it. Hopefully at some point Edge will support returning a window proxy object and supporting `closed` on it. – T.J. Crowder Jun 13 '17 at 10:54
  • 1
    @Abhijeet on Safari it works either, however, I can't check nor IE11 not Edge unfortunately – Sergey Mell Jun 13 '17 at 10:59