Return a value from window.open

馋奶兔 提交于 2019-12-02 18:23:16

I have two ideas that could help you but the first one is tied to CORS, so you won't be able to use it from different domains at least you can access both services and configure them.

FIRST IDEA:

The first one is related to this native api. You could create on the parent window a global function like this:

window.callback = function (result) {
    //Code
}

As you can see it receives a result argument which can hold the boolean value you need. The you could open the popup using the same old window.open(url) function. The popup's onlick event handler could look like this:

function() {
    //Do whatever you want.
    window.opener.callback(true); //or false
}

SECOND IDEA: Solves the problem

The other idea I got is to use this other native api to trigger an event on the parent window when the popup resolves (better known as cross-document messaging). So you could do this from the parent window:

window.onmessage = function (e) {
    if (e.data) {
        //Code for true
    } else {
        //Code for false
    }
};

By this way you are listening to any posted message on this window, and checking if the data attached to the message is true (the user clicks ok in the popup) or false (the user clicks cancel in the popup).

In the popup you should post a message to the parent window attaching a true or a false value when corresponds:

window.opener.postMessage(true, '*'); //or false

I think that this solution perfectly fits your needs.

EDIT I have wrote that the second solution was also tied to CORS but digging deeper I realized that cross-document messaging isn't tied to CORS

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!