为什么在循环内通过setTimeout()调用window.open()默默忽略iff? [英] Why is window.open() silently ignored iff called from within a loop and via setTimeout()?

查看:216
本文介绍了为什么在循环内通过setTimeout()调用window.open()默默忽略iff?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

---编辑.

我不明白.昨天,它似乎被忽略了;现在它似乎正在工作.即使在循环内,也可以通过setTimeout()调用.目前,我似乎很难复制昨天的行为...发生了什么事?

I don't get it; yesterday it seemed to be ignored; now it seems to be working. Even within loop and called via setTimeout(). Currently I seem to be having difficulties replicating yesterday's behaviour... What is going on?

---第2次编辑.

第一个想法如何修复"问题的复制:很奇怪,这是否可行似乎取决于当前URL!例如.作品来自SE网站,但不是来自 http://www.asdf.com/.怎么这样?

First idea how to "fix" the replication of the issue: weirdly, whether or not this works seems to be dependent on the current URL! E.g. works from SE-sites, but not from, say, http://www.asdf.com/. How so?

setTimeout() 在这里工作:

Whereas setTimeout() works here:

setTimeout(function(){ alert("Hello"); }, 3000);

window.open() 在这里工作:

and window.open() works here:

window.open("https://www.bbc.com","_self");

甚至是这两个作品的结合:

and even the combination of the two works here:

setTimeout(function(){ window.open("https://www.bbc.com","_self") }, 3000);

突然而又意外地,两者的组合-默默地-在循环中被忽略:

suddently and unexpectedly the combination of the two is - silently - ignored in a loop:

i=0;
while(i < 100)
{
    setTimeout(function(){ window.open("https://www.bbc.com","_self") }, 3000);
    i++
}

为什么?

tldr;

这个问题似乎已经提出了简洁的问题解答(A& A)格式,但已经提出了将近一百万次,但据我所知/尚未找到.例如

This question seems to have come up close to a million times already but not yet (as far as I could tell / search) with a succinct Q&A format; e.g.

Settimeout()JavaScript函数将被忽略

根据第一原理"模拟JavaScript的setTimeout()方法

推荐答案

弹出窗口在大多数流行的浏览器中,阻止程序仅在由于直接用户操作(例如单击)运行代码而打开新窗口时才允许打开新窗口.由于setTimeout()发生在将来的某个时间,因此不被认为是用户操作的直接结果,因此尝试从setTimeout()打开窗口的尝试可能会被弹出窗口阻止程序阻止.

Popup blockers in most popular browsers will only allow a new window to be opened if it is opened as a result of code running from a direct user action such as a click. Because a setTimeout() happens some time in the future, is not considered the direct result of a user action so attempts to open windows from setTimeout() are likely blocked by the popup blocker.

从本质上讲,尝试从内部触发window.open setTimeout()会使浏览器进行思考",这是一个值得(默默)阻止的弹出窗口. -相比之下,如果window.open是自己触发的,则浏览器似乎将 视为用户点击" ,即不将其视为垃圾邮件被封锁.

In essence, trying to fire window.open from within setTimeout() leaves the browser to "think" it's a popup which deserves (silent) blocking. -- If, in contrast, window.open is fired on it's own, the browser treats seems to treat it like a "user click", that is, not as spam to be blocked.

这篇关于为什么在循环内通过setTimeout()调用window.open()默默忽略iff?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆