最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to navigate to a URL while respecting Ctrl-click opens URL in new tab? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Sep 11, 2020 at 21:12 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 30, 2012 at 21:32 AndyAndy 12k5 gold badges34 silver badges34 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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;
});

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.');
});

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.

发布评论

评论列表(0)

  1. 暂无评论