javascript - Edge 中的 window.postMessage 时无法访问源对象

标签 javascript google-chrome firefox microsoft-edge

我目前正在使用 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: enter image description here
这里出了什么问题,可以做些什么来解决这个问题?

在代码块周围添加了 try-catch,这是我看到的错误。
enter image description here

最佳答案

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

Page1.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>

Page2.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>

结果:

enter image description here

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

关于javascript - Edge 中的 window.postMessage 时无法访问源对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60503466/

相关文章:

javascript - 如何防止 Chrome 在切换选项卡后处理(?)我的 webgl 绘图上下文?

html - CSS 布局中的奇怪 heisenbug

html - Mac 和 Windows 环境下的 Google Chrome 浏览器 for input type=range

javascript - Firefox 中的图像不遵守最大高度

android - IE、Chrome、Firefox 和 Android 浏览器上的 Facebook oauth、FB.getLoginStatus 和 FB.logout

javascript - Div 显示多次且按钮仍处于禁用状态

javascript - 仅在一个地方编写菜单栏

javascript - 我如何确定何时溢出 :hidden parent is overflown 的 child

javascript - JWPlayer Javascript API for Android Webview

javascript - 在基于 iframe 的文本编辑器中禁用 Firefox 和 Chrome 拼写检查