在 jQuery ajax 成功回调中创建时弹出窗口被阻止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1086672/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:38:18  来源:igfitidea点击:

Popup blocked when created in jQuery ajax success callback

jqueryajaxpopup

提问by mark smith

Google Chrome seems to be blocking a popup I am creating via jQuery. After some investigation, it appears to be an issue with calling window.openin the success event of an ajax call. Is there a way around this? My jQuery ajax call returns the URL to be opened. So I am bit stuck.

谷歌浏览器似乎阻止了我通过 jQuery 创建的弹出窗口。经过一番调查,似乎是window.open在 ajax 调用的成功事件中调用的问题。有没有解决的办法?我的 jQuery ajax 调用返回要打开的 URL。所以我有点卡住了。

It works if I place the window.openoutside the ajax call; but, inside (i.e. in the success event) it is blocked. I think it is something to do with CONTEXT but I am unsure.

如果我将window.openajax 调用放在外部,它会起作用;但是,在内部(即在成功事件中)它被阻止了。我认为这与上下文有关,但我不确定。

Here is what I have:

这是我所拥有的:

     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 which is the url returned from service
            // static url below is for testing
            window.open("https://www.myurl.com");  // THIS IS BLOCKED
        },
        error: function(msg) {
            // alert(error);
        }
    });

采纳答案by karim79

Simply open the new window in the success callback:

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

 $.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);
    }
});

Note you might have to set $.ajax's async option to false for that, otherwise the code following the $.ajax call could be evaluated before the response is received.

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

回答by Andrew

As several people have pointed out, the accepted answer no longer works. Based on the comment by aidiakapi, I used a workaround by first opening the window.

正如一些人指出的那样,公认的答案不再有效。根据 aidiakapi 的评论,我首先打开窗口使用了一种解决方法。

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

Then doing the ajax business and in the done()function, open the page with that name.

然后做ajax业务,在done()函数中,打开那个名字的页面。

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

This also doesn't matter if you do it async or not.

如果您异步执行,这也无关紧要。

回答by Code.Town

Your code returns these in firefox and chrome:

您的代码在 Firefox 和 chrome 中返回这些:

Firefox: "Firefox prevented this site from opening a pop-up window." Chrome: "Pop-up blocked"

Firefox:“Firefox 阻止此站点打开弹出窗口。” Chrome:“弹出窗口已阻止”

To fix this issue just add async:false to your ajax call.

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

$.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);
}

});

});

Just be careful that async:false will force javascript to wait for jQuery ajax result. It means it freezes javascript until ajax call is completed.

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

回答by Matt Bridges

Firefox does popup blocking based on the event that causes the javascript code to run; e.g., it will allow a popup to open that was triggered from an onclick, but not one that was triggered by a setTimeout. It has gotten a little bit complicated over the years as advertisers have tried to circumvent firefox's popup blocker.

Firefox 会根据导致 javascript 代码运行的事件来阻止弹出窗口;例如,它将允许弹出窗口打开从一个触发的onclick,而不是一个,是由一个触发setTimeout。多年来,随着广告商试图绕过 Firefox 的弹出窗口拦截器,它变得有点复杂。

回答by Craig

You can still have the code in the success event but async will need to be false.

您仍然可以在成功事件中使用代码,但 async 需要为 false。

回答by zachelrath

Follow the method described in this post:

按照这篇文章中描述的方法进行操作:

window.open without popup blocker using AJAX and manipulating the window.location

window.open 没有使用 AJAX 和操作 window.location 的弹出窗口阻止程序

In a nutshell, the approach is:

简而言之,方法是:

  1. Your code must be initiated by an onclickevent.
  2. Open a new window, perhaps initially with no content, with window.open--- and store a reference to the window so that you can use it later.
  3. In the success callback from your AJAX operation, use window.location.replaceto manipulate the URL of your already-open window with the desired URL.
  1. 您的代码必须由onclick事件启动。
  2. 打开一个新窗口,最初可能没有内容,使用window.open--- 并存储对窗口的引用,以便您以后可以使用它。
  3. 在您的 AJAX 操作的成功回调中,使用window.location.replace所需的 URL 来操作您已经打开的窗口的 URL。

回答by tiepnv

 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);
    }
});

回答by Rameshwor Maharjan

this works for me.

这对我有用。

$(document).ready(function() {
        $('#myLink').on( "click", function() {
            var myNewTab = window.open('about:blank', '_blank');
            $.ajax({
                method: "POST",
                url: "ajax.php",
                data: { name: "John", location: "Boston" },
            })
            .done(function( msg ) {
                myNewTab.location.href = "google.com";
            });
        });
    });

回答by tiepnv

if you put async:true then you must do the following:

如果你把 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);
    }
});