javascript - jQuery 延迟 promise 似乎不适用于打开新窗口

标签 javascript jquery

我目前正在尝试按顺序实现以下工作流程: 1. 如果成功,则检索包含重定向 URI/URL 的 URL。 2. 使用检索到的 URL 打开新窗口,该窗口基本上重定向回同一页面,但现在,该 URL 的后面附加了“code=randomCode”。 3. 解析出 randomCode 以用作其他内容的输入。

问题: 此时,我使用 jQuery promise 首先 $.get(number 1), .then(do number 2), .then(do number 3)。

问题是整个功能似乎只有在一次失败后才能工作。即每次刷新时,新窗口都会第一次打开,但其他部分不会成功,即 randomCode 将不会成功解析出来,因为在该阶段,不知何故 jQuery 无法检测到打开的窗口,即使它应该因为它使用的是 .then。

但是,在第一次失败后,一旦打开窗口,随后的每次尝试都会成功地正确检索所有内容。

这是怎么回事?有人可以帮忙吗?我的代码示例如下:

var retrievedURL;
var desiredString;
function getURL() {

    $(document).ready(function() {
        $.get(firstURL) // assume valid URL
                .then(function(response) {
                    $('#url').html('Click this');
                    $('#url-link').attr("href",response.url);
                    retrievedURL = response.url;
                })
                .then(function() {
                    newWindow = window.open(retrievedURL ,'test');
                })
                .then(function() {
                    desiredString = newWindow.location.search.substr(6);
                })


    })
}

这就是该函数的要点。我当然然后继续用desiredString做一些事情,但不知何故,每次,第一次运行,desiredString都是null。

最佳答案

如果新窗口进行了重定向,那么您就没有考虑它执行此操作的时间。您需要在新窗口上加载事件监听器,然后获取 url

最后一个 then() 不会等待新窗口加载,它几乎会立即被调用。您需要从第二个 then() 返回一个 Promise,以便在该 Promise 解决后触发最后一个 then()

尝试

 $.get(firstURL) // assume valid URL
            .then(function(response) {
                $('#url').html('Click this');
                $('#url-link').attr("href",response.url);
                retrievedURL = response.url;
            })
            .then(function() {
                newWindow = window.open(retrievedURL ,'test');
                // listen for window to load
                newWindow.onload = function(){
                   desiredString = newWindow.location.search.substr(6);
                   // do something with desiredString
                }
            })

关于javascript - jQuery 延迟 promise 似乎不适用于打开新窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516643/

相关文章:

jquery - 删除和返回焦点表单元素中的背景

javascript - 反射(reflection)不起作用

javascript - 将变量值设置为 jquery message + jquery.validate

带有延迟的 JavaScript/jQuery 鼠标悬停事件

javascript - 匹配不可打印/非 ASCII 字符并从文本中删除

javascript - 为什么这个更具体的 CSS 规则没有胜出?

javascript - $ ("#input").val() 在使用 $.post() 时返回未定义

javascript - Backbone.Collection.where 错误 Uncaught TypeError : i. 匹配不是函数

javascript - 简化javascript中for循环的嵌套条件

javascript - 使用 JSON 上传图像不起作用