Open a new tab in the background?

前端 未结 5 1509
闹比i
闹比i 2020-11-22 10:07

Using javascript, I want to open a new page in a different tab, but remain focused on the current tab. I know I can do it like this:

open(\'http://example.co         


        
5条回答
  •  庸人自扰
    2020-11-22 10:17

    THX for this question! Works good for me on all popular browsers:

    function openNewBackgroundTab(){
        var a = document.createElement("a");
        a.href = window.location.pathname;
        var evt = document.createEvent("MouseEvents");
        //the tenth parameter of initMouseEvent sets ctrl key
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                    true, false, false, false, 0, null);
        a.dispatchEvent(evt);
    }
    
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    if(!is_chrome)
    {
        var url = window.location.pathname;
        var win = window.open(url, '_blank');
    } else {
        openNewBackgroundTab();
    }
    

提交回复
热议问题