How to navigate to a URL while respecting Ctrl-click opens URL in new tab?
Asked Answered
M

2

9

I'd like to be able to (from Javascript) navigate as though a link had been clicked (but not necessarily when a link is clicked -- could be another action).

I know window.location.href = '...'; and window.location.replace('...');, but these methods don't allow the user to specify new window, new tab, etc. by holding Cmd (OS X) or Ctrl. I'd like to be able to do it without manually checking the states of these keys.

Megaspore answered 30/5, 2012 at 21:32 Comment(0)
T
6

If you want to handle both clicks, normal and ctrl-click this is what I use :

$("li").on("click", function(e){
    var url = $(this).find("a").attr("href");
    if(e.ctrlKey){
        $('<a href="'+ url + '" target="_blank"></a>')[0].click();
    } else {
        document.location = url;
    }
    return false;
});
Tocsin answered 5/9, 2013 at 15:8 Comment(1)
Any way to not open this in the foreground?Megaspore
T
4

This only works if you do it from a click handler triggered by the user, otherwise, the browser will detect it as an unwanted pop up and block it:

<div id="test">open in new tab</div>

$('#test').click(function(){    
    openInNewTab('http://example.com');
});

function openInNewTab(url)
{
    $('<a href="'+ url + '" target="_blank">open in new tab</a>')[0].click();
}

I think there is no other option since this is a security behavior.

Thaxter answered 5/10, 2012 at 4:9 Comment(1)
It's not ideal, but I'll take it.Megaspore

© 2022 - 2024 — McMap. All rights reserved.