Javascript Bring window to front if already open in window.open?

后端 未结 8 635
别那么骄傲
别那么骄傲 2020-11-30 07:35

If you open a window like:

window.open (\"url\",\"winName\",\"location=0,width=300,height=214\");

If winName is already open i

相关标签:
8条回答
  • 2020-11-30 07:56

    The various answers suggesting using any form of .focus() are likely not going to work in all browsers.

    This used to work back in the day but not any more, mainly due to browsers working to actively stop shady ad networks from pushing their popup ads to the foreground.

    In Mozilla Firefox in particular (depending on your version) there is a configuration setting that is turned on by default that stops other windows (e.g. popups) from focusing themselves.

    You can find this setting in the about:config page (tread carefully!)

    dom.disable_window_flip: true

    If I recall correctly this setting used to be called something like ~"allow_raise_or_lower_windows*

    Other browsers may implement something similar, but quite simply if 1 of the major browsers blocks the use of .focus() by default then there's not much use in attempting to call it.

    As a result, the only solution I've seen that works is to see if the window exists, and is not already closed... and if so close it, then load the window you want.

    function closePopupIfOpen(popupName){
      if(typeof(window[popupName]) != 'undefined' && !window[popupName].closed){
        window[popupName].close();
      }
    }
    

    when opening your popup if there's a chance it is already open (and burried behind other windows) then you can call this function before you attempt to open your popup.

    closePopupIfOpen('fooWin');
    var fooWin = window.open('someURL', 'foo', '...features...');
    

    The drawback of course is that if there was anything "important" (e.g. a form partially filled in) in that window it will be lost.

    0 讨论(0)
  • 2020-11-30 07:58

    I had the same problem, have spent a lot of time to find a solution, finally it works by this:

    var singleWindow;
    function openNewWindow(){
    	if(singleWindow){
    		singleWindow.close();
    	}
    	singleWindow = window.open ("url","winName","location=0,width=300,height=214");
    }
    This close the current window (if exist) and open a new window that will be placed on the top (default behavior)

    Hope this help you !

    0 讨论(0)
提交回复
热议问题