javascript - FireFox 34 中的 "DataCloneError: The object could not be cloned."

标签 javascript local-storage mozilla postmessage

使用给定的函数发布消息,但出现错误“DataCloneError:无法克隆对象。”在行“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'));
               }               
         }
    }
}();

最佳答案

postMessage使用 structured clone algorithm 发送消息在 Firefox 中,因此在发送之前需要调整某些内容。

在您的示例中,消息包含的内容并不明显,但绕过结构化克隆的一种 hack-y 方法是强制执行。通过 postMessage 发送 URL 会抛出错误:

someWindow.postMessage(window.location, '*');
// ERROR

但是您可以这样做来解决它:

var windowLocation = '' + window.location;
someWindow.postMessage(windowLocation, '*');
// WORKS

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

关于javascript - FireFox 34 中的 "DataCloneError: The object could not be cloned.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27558398/

相关文章:

javascript - Angular $modal 范围 - 将对象传递给 $modal

javascript - 存储用户数据的最佳方式

jquery - 本地存储防止页面重新加载

html - 如何更改单选按钮的外观,就像它在 Chrome 中一样

css - 为什么 text-align 的浏览器前缀有不同的行为,哪个是正确的?

api - 使用Mozilla音频API创建提示音

JavaScript 在事件后返回

JavaScript "new Array(n)"和 "Array.prototype.map"怪异

javascript - window.open 在 Google Chrome 中打开标签页和窗口

javascript - 为什么用 !0 而不是 1 或 true 来设置 localStorage.setItem 数据?