在React中使用EventListener和postMessage从弹出窗口传递数据

时间:2019-05-14 07:42:03

标签: javascript reactjs dom oauth-2.0 react-router

我正在使用oAuth登录名,它可以正常工作,但是重定向到授权和响应的整个过程都在同一页面上进行。 我想做的是在弹出窗口中打开它。

为了实现这一点,我必须在父页面中添加一个EventListener(例如,“使用github连接”按钮在其中)。这是代码:

let popup = window.open(window.location.origin+`/socialProcess?site=github`, width=600, height=600);
popup.addEventListener("message", (response) => {
        if (response.origin !== window.location.origin) {
            return;
        }
        let data = response.data;
        if (data.success) {
            alert(this.state.userName + " account accessed successfully");
        }
    }, false);

在通过路由/socialProcess加载的孩子页面中,我首先将弹出页面重新加载到社交网络oAuth url,并且在授权过程之后,响应URI返回到/socialProcess(全部都发生在同一个弹出窗口中)。 然后,使用接收到的数据(经过处理后),我尝试以3种不同的方式将其发送到父侦听器函数:

window.opener.postMessage({success: this.state.success}, this.state.page);
window.postMessage({success: this.state.success}, this.state.page);
parent.postMessage({success: this.state.success}, this.state.page);

但是似乎未触发侦听器的功能。

我认为问题在于加载社交oauth页面时会自动重新加载弹出页面,然后是响应URI。 因为如果我在重新加载之前添加window.postMessage({success: true}, this.state.page);,我的父页面就会获得数据。

最让我感到困惑的是,如果我在window.opener.location.reload();下添加postMessage(在弹出窗口重新加载之后),我的父页面会重新加载,这意味着它确实记得是谁打开了它,为什么{{1 }}不起作用?弹出窗口重新加载后,听众会死吗?

我在做什么错?还有其他方法吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

我能够解决我的问题。 首先,这里是正确的postMessage:RBergomiST_instance=convertMat2Ptr<RBergomiST>(RBergomiST(x, HIn, e, r,t, k, NIn, MIn));

在我的示例中,我传递了window.postMessagewindow.postMessage({success: this.state.success}, this.state.page);的值必须是字符串,因为侦听器希望接收到“消息”。

这意味着我必须使用例如Json stringify将任何对象转换为字符串。

这样做并把我的值作为字符串传递(然后解析)解决了我的问题。