请注意,这不适用于实时网站;这只是我自己的一些尝试。我在 Mac OSX 10.9.3 上运行 Chrome 版本 35.0.1916.153(最新)。
正如许多其他人尝试做的那样,我正在尝试让 JavaScript 在新选项卡中打开链接。那里有很多例子,但我无法让其中任何一个发挥作用。最有前途的想法似乎是模拟 anchor 上的 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>
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);
});
我做错了什么?
最佳答案
问题是,当您尝试以编程方式打开新窗口/选项卡时,浏览器通常会阻止您的代码。
因此,新的选项卡/窗口打开始终必须由用户操作触发。 (否则我们总是会充满弹出广告)
因此,首先,确保您的 js 是在用户事件上执行的,然后您应该能够使用 window.open
。
JsFiddle example
html:
<a href="//google.com" target="blank">new tab google</a>
<button class="user">user triggered</button>
<button class="programatic">programatic</button>
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);
关于javascript - 无法使用 JavaScript/jQuery 打开新选项卡或窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24478163/