Javascript 允许 window.open 打开新窗口而不是弹出窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14643040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow window.open to open new window and not popup
提问by Emerson Maningo
I have this JS code:
我有这个JS代码:
window.open(loginurl, '_blank');
coming from a condition for example:
来自一个条件,例如:
if (userloggedin) {
//popup another page
} else {
window.open(loginurl, '_blank');
}
"loginurl" is an login URL that I would like to open in new window.
“loginurl”是我想在新窗口中打开的登录 URL。
Problem: This will be blocked in most browsers (Firefox and Chrome) because it behaves like a popup.
问题:这将在大多数浏览器(Firefox 和 Chrome)中被阻止,因为它的行为类似于弹出窗口。
I would like a solution that will still utilizes my login URL variable (not altering the if else statement), open it in new window without any warnings of a popup that is being blocked.
我想要一个仍然使用我的登录 URL 变量(不改变 if else 语句)的解决方案,在新窗口中打开它,而没有任何被阻止弹出窗口的警告。
I am searching for ways but I never found a solution. If somebody can provide some tips or insights. That would be highly appreciated.
我正在寻找方法,但我从未找到解决方案。如果有人可以提供一些提示或见解。这将不胜感激。
Thanks.
谢谢。
回答by Beat Richartz
The window opened by window.openwill always be regarded as a pop-up to block by browsers when the function is triggered without a user action initiating it.
window.open当该功能被触发而没有用户操作启动它时,被打开的窗口将始终被视为一个弹出窗口以阻止浏览器。
That means that for example that these will not be blocked:
这意味着例如这些不会被阻止:
$('a').on('click.open', function(e) { e.preventDefault(); window.open('http://disney.com') });
Chrome even allows other events to trigger the popup, while firefox will not allow this:
Chrome 甚至允许其他事件触发弹出窗口,而 Firefox 不允许:
$(document).on('keydown', function(e) { window.open('http://stackexchange.com') });
And this will be blocked:
这将被阻止:
$(document).ready(function() { window.open('http://stackoverflow.com') });
So, unless you're triggering the window.openafter a user action, you can never be sure that your window won't be blocked.
因此,除非您在window.open用户操作之后触发,否则您永远无法确定您的窗口不会被阻止。
回答by Aqua Huang
This way won't block your popup:
这种方式不会阻止您的弹出窗口:
$.ajax({
url:"url",
dataType: "text",
cache: false,
success: function(data){
window.open('url','_self');
}
});

