Open link in new window or focus to it if already open

前端 未结 6 2171
轮回少年
轮回少年 2020-12-03 02:37

I have a link which should open in a new tab, but if the tab is already open, just switch to it. I\'ve tried with javascript, wnd = window.open() and than wnd.focus(), that

相关标签:
6条回答
  • 2020-12-03 03:05

    Different browsers behave differently for window.open() and focus(). For this code window.open('www.sample.com','mywindow').focus()

    • Chrome 20 opens a new tab, and focuses on subsequent open() calls regardless if focus() is called or not.
    • Firefox 13 opens a new tab, focuses on first open(), does not focus on subsequent open() calls/disregards focus().
    • IE 8 opens a new window, honors focus().
    • Safari 5 opens a new window, and focuses on subsequent open() calls regardless if focus() is called or not.

    Fiddle to test with: http://jsfiddle.net/jaraics/pEG3j/

    0 讨论(0)
  • 2020-12-03 03:16

    If you are not interested in retaining the state of a previously opened tab, you can do this:

    var loadingTableWnd;
    function openOrSwitchToWindow(url) {
        if (loadingTableWnd != undefined) {
            loadingTableWnd.close();
        }
        loadingTableWnd = window.open(url,'myFrame');
    }
    
    0 讨论(0)
  • 2020-12-03 03:19

    You shouldn't need any logic for something like this. By default, specifying the second parameter for window.open() gives the window a "name", that the browser remembers. If you try to call window.open() with the same name (after it's already been opened), it doesn't open a new window...but you might still need to call .focus() on it. Try this:

    var a = window.open(url, "name");
    a.focus();
    

    Those should be the only lines of code in your function, and you don't need the loadingTableWnd variable...

    0 讨论(0)
  • 2020-12-03 03:21

    In Firefox 66 and Chrome 74 this works for me:

     wnd = window.wnd && window.wnd.close() || window.open(url, "wnd");
    

    Not tested in other browsers. Thanks to roberto (in the comment of the MarkZ answer) to point me on this solution. (I could not add a comment in that answer due my lack of reputation, sorry).

    window.focus() solution was not fit my needs as this other one.

    0 讨论(0)
  • 2020-12-03 03:22

    window.focus() is widely supported and seems to be working fine in both Internet Explorer and Firefox for me, the problem should be in your code. I've created a simple jsFiddle for you to test.

    0 讨论(0)
  • 2020-12-03 03:26

    If the window is already opened and if you want to focus on that window you can use

    window.open('', 'NameOfTheOpenedWindow').focus();
    
    0 讨论(0)
提交回复
热议问题