top.postMessage原始错误没有被捕获

Ari*_*ael 14 javascript postmessage try-catch

我正在尝试与postMessage实现通信.有一个主页面打开一个带有iframe的弹出窗口,它来自不同的域.到目前为止这工作正常但我想捕获以下错误,当我打开具有错误原点的iFrame时会发生这种错误.

无法在'DOMWindow'上执行'postMessage':提供的目标原点('myOriginURL')与收件人窗口的原点('myWindowsOrigin')不匹配.

origin = 'http://www.myorigin.ch';
if (window.postMessage) {
  try {
     top.postMessage('hello', origin);
  } 
  catch(ex) {
     alert('an error occured');
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是代码永远不会进入catch块.有趣的是,chrome在控制台中显示错误,而所有其他主要浏览器都没有做任何事情(没有警报,没有错误)

如何处理postMessage中的错误?

Mad*_*ist -4

这是因为错误发生在您加载到 iFrame 中的域中。用块包围发布消息的代码try{}catch(e){},并向侦听器发送适当的错误消息以在其中处理它。

try{
parent.postMessage({"success":true,"usertoken":localStorage.token},"*");
}
catch(e){
parent.postMessage({"success":false},"*");

}
Run Code Online (Sandbox Code Playgroud)