为什么 window.open() 静默忽略 iff 从循环内通过 setTimeout() 调用?
Why is window.open() silently ignored iff called from within a loop and via setTimeout()?
--- 编辑。
我不明白;昨天它似乎被忽略了;现在它似乎正在工作。即使在循环内并通过 setTimeout()
调用。目前我似乎难以复制昨天的行为...这是怎么回事?
--- 第二次编辑。
第一个想法是如何 "fix" 问题的复制:奇怪的是,这是否有效似乎取决于当前的 URL!例如。作品 , but not from, say, 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.
本质上,试图从内部 setTimeout()
触发window.open
会让浏览器“思考”这是一个值得(无声)阻止的弹出窗口。 -- 相反,如果 window.open
是自己触发的,浏览器似乎将其 视为“用户点击” , 即不作为垃圾邮件被拦截。
--- 编辑。
我不明白;昨天它似乎被忽略了;现在它似乎正在工作。即使在循环内并通过 setTimeout()
调用。目前我似乎难以复制昨天的行为...这是怎么回事?
--- 第二次编辑。
第一个想法是如何 "fix" 问题的复制:奇怪的是,这是否有效似乎取决于当前的 URL!例如。作品
而 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.
本质上,试图从内部 setTimeout()
触发window.open
会让浏览器“思考”这是一个值得(无声)阻止的弹出窗口。 -- 相反,如果 window.open
是自己触发的,浏览器似乎将其 视为“用户点击” , 即不作为垃圾邮件被拦截。