Javascript window.open 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11821009/
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
Javascript window.open not working
提问by Quinn Finney
Ok. I'm trying to login to twitter. The window is not opening in this code. The response that gets alerted is not null and is a link to a login screen. Any ideas?
好的。我正在尝试登录推特。该窗口未在此代码中打开。收到警报的响应不为空,并且是登录屏幕的链接。有任何想法吗?
var url = "./twitter_login.php";
var con = createPHPRequest();
con.open("POST",url,true);
con.setRequestHeader("Content-type","application/x-www-form-urlencoded");
con.send("");
var response = "";
con.onreadystatechange = function() {
if(con.readyState==4 && con.status==200) {
response = con.responseText;
alert(response);
window.open(response,"twitter","menubar=1,resizable=1,width=350,height=500");
}
}
回答by jfriend00
The standard popup-blocker logic contained in most browsers these days will block any calls to window.open()
that are not the direct result of a user action. Code that is triggered by timers or by any asynchronous callback (like your ajax ready function) will be treated as NOT caused directly by user actions and the new popup window will generally be blocked.
window.open()
如今,大多数浏览器中包含的标准弹出窗口阻止程序逻辑将阻止任何不是用户操作直接结果的调用。由计时器或任何异步回调(如您的 ajax 就绪函数)触发的代码将被视为不是由用户操作直接引起的,并且新的弹出窗口通常会被阻止。
You can verify this is what is happening by temporarily changing your browser's popup blocking (turning it off) and see that it then starts working.
您可以通过临时更改浏览器的弹出窗口阻止功能(将其关闭)来验证这是发生了什么,然后查看它是否开始工作。
Probably what you need to do as a work-around is to create the window upon the user action that started this thread of code and then put the content into the window when you get your ajax response. The browser will probably allow that. I know that's less desirable from a visual perspective, but you can put some temporary content in the window until the ajax response comes in (something like "loading...").
您可能需要做的解决方法是根据启动此代码线程的用户操作创建窗口,然后在您收到 ajax 响应时将内容放入窗口。浏览器可能会允许这样做。我知道从视觉角度来看这不太理想,但是您可以在窗口中放置一些临时内容,直到 ajax 响应出现(类似于“正在加载...”)。
回答by t_warsop
Just had this exact same issue. Just in case you wanted the code that fixed it. I used this:
刚刚有这个完全相同的问题。以防万一你想要修复它的代码。我用过这个:
newWindow = window.open("", "_blank");
request = $.ajax({ ... my request which returns a url to load ... })
request.done((function(_this) {
return function(data, textStatus, jqXHR) {
return newWindow.location = data.Url;
};
})(this));