JavaScript - 尝试和捕获 - 捕获Window.postMessage()错误

Kev*_*n M 15 javascript iframe jquery html5 cross-domain

我在使用window.postMessage()时遇到错误.

我希望能够捕获我得到的错误 -

"无法向http://www.that-domain.com发布消息.收件人来源http://www.this-domain.com

简单的示例代码(应该是错误):

 try {
    window.postMessage('1','http://www.differentDomain.com');
 } 
 catch (e) {       
     alert('error');
 }
Run Code Online (Sandbox Code Playgroud)

更详细的流程:我使用jQuery向文档添加跨域iframe,然后发布到它.这不应该是错误,因为目标来源应该匹配 - 它们都由proxyDomain变量设置.

var $iframeProxy = $('<iframe id="myIFrame" src="' + proxyDomain + '"></iframe>').appendTo('body');

window.storageProxy = $iframeProxy[0].contentWindow;

try {
    window.storageProxy.postMessage(message, proxyDomain);
}
catch (e) {       
    alert('error');
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*nta 7

无法捕获错误,但通常如果目标来源不同,则会发生错误,这种情况是测试与生产场景。

因此,您可以检查什么是父域并相应地更改目标来源:

function getTargetOrigin()
{
    try {
        var url = (window.location != window.parent.location) ? document.referrer : document.location.href;
        if (url.indexOf('www.myproduction-website.com')!=-1)
            return document.location.protocol + '//www.myproduction-website.com'
        else //set the alternative target
            return document.location.protocol + '//' + url.split('/')[2];
    }
    catch(e) //falback to production
    {
        return document.location.protocol + '//www.myproduction-website.com'
    }
}
Run Code Online (Sandbox Code Playgroud)

并在 postMessage 函数中使用它:

function postMessage(message){
    window.top.postMessage( message,getTargetOrigin());
}
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,您可以在多个服务器配置中使用相同的代码,而无需对 targetOrigin url 进行硬编码。

如果您在框架内导航并重新检查 document.referrer,则此解决方案将失败,在这种情况下,它将不包含父 url,而是包含前一个框架 url。在这种情况下,请考虑使用“*”作为 targetOrigin url,这是将消息发送到其他域的唯一可行解决方案。

希望能帮助到你!

  • 只是为了支持这个答案,来自 MDN:“与任何异步调度的脚本(超时,用户生成的事件)一样,postMessage 的调用者不可能检测到监听 postMessage 发送的事件的事件处理程序何时抛出异常.” https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch (2认同)

Kev*_*n M 4

看起来 HTML5 规范中概述了如果域来源不匹配,则不会抛出任何错误,并且应该静默中止。

http://www.whatwg.org/specs/web-apps/current-work/multipage/web-messaging.html#web-messaging

10.4.3 发布消息 - 第 9 部分

“...如果 targetOrigin 参数是绝对 URL,并且调用该方法的 Window 对象的 Document 与 targetOrigin 没有相同的来源,则静默中止这些步骤。”

  • 是啊,但是你怎么能保持沉默并抓住这一点呢? (12认同)