javascript - 为什么 window.open() 会默默地忽略 iff 从循环内并通过 setTimeout() 调用?

标签 javascript firefox popup timeout

---编辑。

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

<小时/>

---第二次编辑。

第一个想法如何“修复”问题的复制:奇怪的是,这是否有效似乎取决于当前的 URL!例如。作品from SE-sites ,但不是来自,例如 http://www.asdf.com/ 。怎么会这样?

<小时/>

setTimeout() 在这里工作:

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

window.open()在这里工作:

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

甚至是两者的结合:

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

突然且出乎意料地,两者的组合在循环中默默地被忽略:

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

为什么?

<小时/>

tldr;

这个问题似乎已经出现了近一百万次,但还没有(据我所知/搜索)采用简洁的问答格式;例如

Settimeout() javascript function is ignored

Simulating JavaScript's setTimeout() method “from first principles”

最佳答案

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 自行触发,则浏览器似乎将其视为“用户点击”,也就是说,不会作为垃圾邮件被阻止。

关于javascript - 为什么 window.open() 会默默地忽略 iff 从循环内并通过 setTimeout() 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326060/

相关文章:

android - Eclipse 不显示属性弹出窗口

javascript - 生日日期自动生成 18 岁年份

javascript - 在 firefox 插件中监听 http 响应时识别 XHR(ajax)响应

firefox - 响应式 iframe 中的 YouTube 视频未在 Firefox 中显示

php - 如何将mysql数据放入弹出窗口?

java - 使用 Java 在 Selenium WebDriver (selenium 2) 中处理警报

javascript - 需要知道 jqModal 关闭弹出窗口的命令

匹配 '.' 且前面没有 '\' 的 Javascript 正则表达式(lookbehind alternative)

javascript - 使用带有结构化过滤器的 bootgrid 更新 Change.search 上的参数变量

css - 推特 Bootstrap : Getting Form Inputs and Buttons to be same the height in Chrome and Firefox