"DataCloneError:无法克隆该对象." 在FireFox 34中

Kri*_*hna 9 javascript mozilla postmessage local-storage

使用给定的函数发布消息,但收到错误"DataCloneError:无法克隆该对象".at line"target ['postMessage'](message,target_url.replace(/([^:] +:// [^ /] +).*/,'$ 1'));" 在FireFox-34中,相同的代码在Chrome和旧版FireFox上运行良好.

var storage = function() {
    return {
           postMessage : function(message, target_url, target) {
           if (!target_url) { 
              return; 
           }
           var target = target || parent;  // default to parent
           if (target['postMessage']) { 
                   // the browser supports window.postMessage, so call it with a targetOrigin
                   // set appropriately, based on the target_url parameter.
                   target['postMessage'](message, target_url.replace( /([^:]+:\/\/[^\/]+).*/, '$1'));
               }               
         }
    }
}();
Run Code Online (Sandbox Code Playgroud)

Mic*_*son 12

postMessage在Firefox中使用结构化克隆算法发送消息,因此在发送之前需要调整某些内容.

在你的例子中,消息包含的内容并不明显,但是围绕结构化克隆的一种黑客方式就是强制一点.发送URL postMessage会导致错误:

someWindow.postMessage(window.location, '*');
// ERROR
Run Code Online (Sandbox Code Playgroud)

但你可以这样做来解决它:

var windowLocation = '' + window.location;
someWindow.postMessage(windowLocation, '*');
// WORKS
Run Code Online (Sandbox Code Playgroud)

有更好的方法来处理这个问题,但是对于你提供的内容,至少应该允许一致的行为.

  • 我偶然发现了这个答案,这导致我使用字符串转换来解决我的问题,我建议简单地使用 `window.location.href`,这是“tostring”方法将引用的值,谢谢。 (2认同)