弹出窗口阻塞,jquery window.open成功:AJAX? 外面好的

任何人都可以帮助,我有一些jquery和chrome阻止我正在创建的弹出窗口。 经过一些调查后,在ajax调用的成功事件中, window.open似乎是一个问题。 这有什么办法吗? 我的jquery ajax调用需要返回我需要打开的URL,所以我有点卡住了。

如果我将open.window放在ajax调用之外它可以工作,但是在内部(成功)它被阻止。 我认为这与CONTEXT有关,但我不确定……

任何想法真的很感激……

这是我有的:

  window.open("https://www.myurl.com"); // OUTSIDE OF AJAX - no problems // with popup $.ajax({ type: "POST", url: "MyService.aspx/ConstructUrl", data: jsonData, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Normally loads msg.d that is the url that is returned from service but put static url in for testing window.open("https://www.myurl.com"); // THIS IS BLOCKED }, error: function(msg) { //alert(error); } }); 

只需在成功回调中打开新窗口:

  $.ajax({ type: "POST", url: "MyService.aspx/ConstructUrl", data: jsonData, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { window.open("https://www.myurl.com"); }, error: function(msg) { //alert(error); } }); 

请注意,您可能必须将$ .ajax的async选项设置为false,否则可以在收到响应之前评估$ .ajax调用之后的代码。

有几个人指出,接受的答案不再适用。 根据aidiakapi的评论,我首先打开窗口使用了一种解决方法。

 window.open("about:blank", "myNewPage"); 

然后执行ajax业务并在done()函数中,打开具有该名称的页面。

 window.open("/foo.html", "myNewPage"); 

如果您执行异步操作也无关紧要。

您的代码在firefox和chrome中返回:

Firefox:“Firefox阻止该网站打开弹出窗口。” Chrome:“弹出窗口被阻止”

要解决此问题,只需在您的ajax调用中添加async:false即可。

 $.ajax({ type: "POST", async: false, url: "MyService.aspx/ConstructUrl", data: jsonData, contentType: "application/json; charset=utf-8", dataType: "json", success: function(url) { window.open(url); }, error: function(msg) { //alert(error); } 

});

请注意,async:false会强制javascript等待jQuery ajax结果。 这意味着它冻结javascript直到ajax调用完成。

Firefox根据导致javascript代码运行的事件执行弹出窗口阻止; 例如,它将允许弹出一个由onclick触发的弹出窗口,而不是由setTimeout触发的弹出窗口。 多年来,由于广告商试图规避firefox的弹出窗口拦截器,它已经变得有点复杂。

您仍然可以在成功事件中获得代码,但异步将需要为false。

按照这篇文章中描述的方法:

window.open没有弹出窗口阻止程序使用AJAX并操纵window.location

简而言之,方法是:

  1. 您的代码必须由onclick事件启动。
  2. 打开一个新窗口,可能最初没有内容,使用window.open —并存储对窗口的引用,以便您以后可以使用它。
  3. 在AJAX操作的成功回调中,使用window.location.replace操作已打开窗口的URL和所需的URL。
  if you put async:true then you must do the following: var safariOP = window.open("https://www.myurl.com"); // DEFINE BEFORE AJAX CALLBACK $.ajax({ type: "POST", url: "MyService.aspx/ConstructUrl", data: jsonData, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { if(safariOP){ safariOP.focus(); // IT'S OK ON SAFARI } }, error: function(msg) { //alert(error); } }); 

如果你把async:true,那么你必须执行以下操作:

 var safariOp = window.open("https://www.myurl.com"); //define before callback ajax contains url . $.ajax({ type: "POST", url: "MyService.aspx/ConstructUrl", data: jsonData, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { //it's ok on safari safariOp.focus(); }, error: function(msg) { //alert(error); } });