简体   繁体   中英

In Google Chrome, how do I bring an existing popup window to the front using javascript from the parent window?

I would like to have a button on a web page with the following behavior:

  • On the first click, open a pop-up.
  • On later clicks, if the pop-up is still open, just bring it to the front. If not, re-open.

The below code works in Firefox (Mac & Windows), Safari (Mac & Windows), and IE8. (I have not yet tested IE6 or IE7.) However, in Google Chrome (both Mac & Windows) later clicks fail to bring the existing pop-up to the front as desired.

How can I make this work in Chrome?

<head>
  <script type="text/javascript">
    var popupWindow = null;
    var doPopup = function () {
      if (popupWindow && !popupWindow.closed) {
        popupWindow.focus();
      } else {
        popupWindow = window.open("http://google.com", "_blank",
          "width=200,height=200");
      }
    };
  </script>
</head>

<body>
  <button onclick="doPopup(); return false">
    create a pop-up
  </button>
</body>

Background: I am re-asking this question specifically for Google Chrome, as I think I my code solves the problem at least for other modern browsers and IE8. If there is a preferred etiquette for doing so, please let me know.

You can't. Window.focus is disabled in Chrome for security reasons, and that is unlikely to change.

You have to close and repopen the respective window.

Why not just do a popopWindow.focus() after the window.open call? It won't hurt to do it there too, and it should ensure that your new window is shown on top of the current one.

You need to set original window to blur and the new window to focus.

var popup = {  //popup = object literal representing your popup
    execute = (function () {
        popup.win = window.open();
        popup.win.focus();
    }());
};
window.blur();

The following code works for me when called in a onclick handler:

var popup = window.open('', 'popup-name', 'resizable,width=480=height=575');

if(popup.location == 'about:blank') {
    popup.location = 'http://google.com';
    return;
}

This code works by trying to access the popup's location, if its about:blank its a new popup and the url is set. Otherwise if the window with the same name 'popup-name' is already open the popup comes into focus. This code does need to be called from a onclick handler otherwise it will not work.

As of today, just calling focus() on the reference to the popup just works and brings the window to the front. I am using Chrome version 62

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