简体   繁体   中英

Opening new tab when clicking on a link in my website keeping the current tab active

I have this code that does what I need. It opens the link in another tab but it moves to the newly opened tab leaving the current tab I'm in. I want it to keep my current tab active and newly opened tab just opened.

function loadpopunder() {
                var clicked = false;
                $('a').each(function() {
                    this.onclick = function() {
                        var a = document.createElement("a");
                        a.href = "http://sitetopopeninnewtab.com";
                        if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
                        {
                            a.target = "_blank";
                        }
                        if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
                        {
//                        var evt = new MouseEvent('click', {'view': window, 'bubbles': true, 'cancelable': true, });
                            var evt = document.createEvent("MouseEvents");
                        }
                        else {
//                        var evt = new MouseEvent('click', {'view': window, 'bubbles': true, 'cancelable': true, 'metaKey': true, 'ctrlKey': true});
                            var evt = document.createEvent("MouseEvents");
                        }
                        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
                        if (clicked == false) {
                            a.dispatchEvent(evt);
                            clicked = true;
                        }
                    }
                });


if(window.location.href == 'http://mymainwebsite.com/'){
    loadpopunder();
}

This can't be done properly, because you depend on the browser settings. Even when you open a url in a new tab with target='_blank' , if the browser is set to open new pages in a pop-up window, you wont get a new tab.

You should check some other SO answer about it here and here .

You can see on the comments that all browser have different behaviors. You can, however, manage new opened windows with javascript window object

Other thing that you can do, is check if the window is focused or not, by using the javascript visibility api .

Hope that helps.

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