如何使用在 getScript 回调函数中生成的 URL 打开新窗口,并避免弹出窗口阻止程序?

2022-01-20 00:00:00 popup jquery javascript ajax

我遇到的问题是,当我尝试执行以下代码之类的操作时,窗口将被弹出窗口阻止程序阻止.我正在使用 getScript 以便可以发出跨域请求.我正在使用 jQuery 1.4.2 来执行以下操作.

The issue I am having is when I try to do something like the below code, the window will be blocked by pop-up blockers. I am using getScript so that I can make cross domain requests. I am using jQuery 1.4.2 to do the below.

将被阻止的代码示例:

//Code that gets blocked by pop-up blockers
$(document).ready(function(){
    $(".popup").click(function(){
        $.getScript("URL_To_A_Javascript_File", function(){
            window.open("dynamicURL", "_blank");
        });
    });
});

通过拦截器但未及时获取 URL 的代码示例:

//This code will get past the pop-up blocker, but the var url won't be updated 
//with the dynamicURL before the window.open() fires in browsers 
//like safari or chrome.
$(document).ready(function(){
    var url;
    $(".popup").click(function(){
        $.getScript("URL_To_A_Javascript_File", function(){
            url = "dynamicURL";
        });
        window.open(url, "_blank");
    });
});

如何使用在 getScript 回调函数中生成的 URL 打开一个新窗口,并避免弹出窗口拦截器?

How can I open a new window using a URL that is generated inside the getScript callback function, and avoid pop-up blockers?

推荐答案

好吧,看来我终于想通了该怎么做.

Ok, it looks like I finally figured out how to do what I was trying to do.

这种方式允许我在不需要处理 javascript 的中间页面的情况下进行弹出窗口.

This way allows me to do the pop-up with out the need for an intermediate page that handles the javascript.

var newWin;
$(document).ready(function(){
    $(".popup").click(function(){
        newWin = window.open();

        $.getScript("URL_To_A_Javascript_File", function() {
            newWin.location = "DynamicURL";
        });
        return false;
    });
});

相关文章