无法使用javascript/jquery打开新选项卡或窗口

Sag*_*ual 0 html javascript jquery javascript-events

请注意,这不适用于实时网站; 这只是我自己丰富的一些实验.我在Mac OSX 10.9.3上运行Chrome版本35.0.1916.153(最新).

正如许多其他人试图做的那样,我正试图让javascript在新标签中打开一个链接.那里有很多例子,但我不能让它们中的任何一个起作用.最有希望的想法似乎是模拟锚点上的cmd +点击.发生click事件,并且事件对象的metaKey属性设置为true,正如我在添加单击处理程序时所看到的那样,但是没有打开URL:没有新窗口,没有新选项卡.

HTML:

<a id="still" href="gv__.html?pictureMode=still" target="_blank">still</a>
<a id="motion" href="gv__.html?pictureMode=motion" target="_blank">motion</a>
Run Code Online (Sandbox Code Playgroud)

JS:

$(document).ready(function() {
    var e = $.Event( "click", { metaKey: true } );

    $("a#motion").trigger(e);
    $("a#still").trigger(e);
    $("a#motion").trigger(e);
    $("a#still").trigger(e);
});
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Mat*_*yas 5

问题是,当您尝试以编程方式打开新窗口/选项卡时,浏览器通常会阻止您的代码.

因此,用户操作始终必须触发新的标签/窗口开口.(否则我们总是满满的弹出式广告)

首先,确保你的js是在用户事件上执行的,然后你应该能够使用window.open.

JsFiddle的例子

HTML:

<a href="//google.com" target="blank">new tab google</a>

<button class="user">user triggered</button>
<button class="programatic">programatic</button>
Run Code Online (Sandbox Code Playgroud)

JS:

$('a').on('click', function(e) {
    console.log('clicked', e);
    // unfortunately although we simulated 
    // the click on the <a/> , it will still 
    // not launch a new window - idk why.
    // therefore we can use the line below
    // to open the <a>'s href in a new tab/window
    // NOTE: this will only occur if the execution was
    // triggered by the user
    window.open(e.currentTarget.href);
});

var simulateClick = function(origEv) {
    var e = $.Event("click");
    e.ctrlKey = true;
    e.metaKey = true;
    e.originalEvent = origEv;
    $('a').trigger(e);
};

$('button.user').on('click', function(e) {
    // this call will actually open a window
    simulateClick(e);
});

$('button.programatic').on('click', function(e) {
    // this will result in a blocked popup
    $.get('/someurl').always(function() {
        // executes the method after a non-user event
        // results in blocked popup
        simulateClick(e);
    });
});

// this will result in a blocked popup
setTimeout(simulateClick, 1000);
Run Code Online (Sandbox Code Playgroud)