首页 > 解决方案 > Edge 中的 window.postMessage 时无法访问源对象

问题描述

我目前正在使用Edge 44.18362,我有一个身份验证窗口和一个打开它的父窗口,一旦身份验证完成,我将消息发布到父级(开启器窗口),如下所示:

$window.opener.postMessage(data,URL);

我正在像这样在父窗口中收听事件:

window.addEventListener('message', someFunc, false);

并且someFunc()定义如下:

function someFunc(windowData){
//here I am accessing source as windowData.source
}

我正在尝试访问source属性MessageEvent以访问 URL 和内容。在 Chrome/Firefox 中,我能够访问source对象和功能工作正常,但是当涉及到 Edge 时,我无法访问source对象并且我在控制台中看到此错误。 这里出了什么问题,可以做些什么来解决这个问题?
!0:
在此处输入图像描述

在代码块周围添加了 try-catch,这是我看到的错误。 在此处输入图像描述

标签: javascriptgoogle-chromefirefoxmicrosoft-edge

解决方案


我使用以下代码示例进行了测试,它可以在 Edge 中正常工作:

页1.html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script>
        function openChild() {
            var childwin = window.open('Page2.html', 'popup', 'height=300px, width=500px');
        }

        window.addEventListener("message", (event) => {
            let txt = document.querySelector('#txtMsg');
            txt.value = `Name is ${event.data.pName} Age is  ${event.data.pAge}`;
            console.log(event.source);  //update: get event.source
        });
    </script>
</head>
<body>
    <form>
        <fieldset>
            <input type='button' id='btnopen' value='Open child' onclick='openChild();' />
            <input type='text' id='txtMsg' />
        </fieldset>
    </form>
</body>
</html>

页面2.html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script>
        function sendMessage() {
            let msg = { pName: "Bob", pAge: "35" };
            window.opener.postMessage(msg, 'http://domain_name/Page1.html')
            window.opener.focus();
        }
    </script>
</head>
<body>
    <form>
        <fieldset>            
            <input type='button' id='btnSendMsg' value='Send Message' onclick='sendMessage();' />
        </fieldset>
    </form>
</body>
</html>

结果:

在此处输入图像描述

您可以参考示例,如果仍然无法正常工作,请提供可以重现问题的最小示例。仅使用您提供的上述代码,我无法重现该问题。


推荐阅读