Chrome sendrequest 错误:类型错误:将循环结构转换为 JSON

我有以下...

chrome.extension.sendRequest({
  req: "getDocument",
  docu: pagedoc,
  name: 'name'
}, function(response){
  var efjs = response.reply;
});

它调用以下内容..

case "getBrowserForDocumentAttribute":
  alert("ZOMG HERE");
  sendResponse({
    reply: getBrowserForDocumentAttribute(request.docu,request.name)
  });
  break;

但是,我的代码永远不会到达“ZOMG HERE”,而是在运行时抛出以下错误chrome.extension.sendRequest

 Uncaught TypeError: Converting circular structure to JSON
 chromeHidden.JSON.stringify
 chrome.Port.postMessage
 chrome.initExtension.chrome.extension.sendRequest
 suggestQuery

有没有人知道是什么原因造成的?


答案 1

这意味着您在请求中传递的对象(我猜是)具有循环引用,如下所示:pagedoc

var a = {};
a.b = a;

JSON.stringify无法转换这样的结构。

注意:DOM节点就是这种情况,它们具有循环引用,即使它们没有附加到DOM树。每个节点都有一个所有者文档,在大多数情况下都引用它。 至少通过对 DOM 树的引用,并再次引用,这只是 DOM 树中多个循环引用之documentdocumentdocument.bodydocument.body.ownerDocumentdocument


答案 2

根据Mozilla的JSON文档,有第二个参数,可用于在解析树时过滤/忽略子项。但是,也许您可以避免循环引用。JSON.stringifyreplacer

在 Node.js我们不能。所以我们可以做这样的事情:

function censor(censor) {
  var i = 0;
  
  return function(key, value) {
    if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value) 
      return '[Circular]'; 
    
    if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
      return '[Unknown]';
    
    ++i; // so we know we aren't using the original object anymore
    
    return value;  
  }
}

var b = {foo: {bar: null}};

b.foo.bar = b;

console.log("Censoring: ", b);

console.log("Result: ", JSON.stringify(b, censor(b)));

结果:

Censoring:  { foo: { bar: [Circular] } }
Result: {"foo":{"bar":"[Circular]"}}

不幸的是,在它自动假设它是循环之前,似乎最多有30次迭代。否则,这应该有效。我甚至从这里开始使用,但在30次迭代后仍然抛出异常。尽管如此,如果您真的需要它,在顶层获得对象的体面表示就足够了。也许有人可以对此进行改进?在 Node.js对于 HTTP 请求对象,我得到:areEquivalentJSON.stringify

{
"limit": null,
"size": 0,
"chunks": [],
"writable": true,
"readable": false,
"_events": {
    "pipe": [null, null],
    "error": [null]
},
"before": [null],
"after": [],
"response": {
    "output": [],
    "outputEncodings": [],
    "writable": true,
    "_last": false,
    "chunkedEncoding": false,
    "shouldKeepAlive": true,
    "useChunkedEncodingByDefault": true,
    "_hasBody": true,
    "_trailer": "",
    "finished": false,
    "socket": {
        "_handle": {
            "writeQueueSize": 0,
            "socket": "[Unknown]",
            "onread": "[Unknown]"
        },
        "_pendingWriteReqs": "[Unknown]",
        "_flags": "[Unknown]",
        "_connectQueueSize": "[Unknown]",
        "destroyed": "[Unknown]",
        "bytesRead": "[Unknown]",
        "bytesWritten": "[Unknown]",
        "allowHalfOpen": "[Unknown]",
        "writable": "[Unknown]",
        "readable": "[Unknown]",
        "server": "[Unknown]",
        "ondrain": "[Unknown]",
        "_idleTimeout": "[Unknown]",
        "_idleNext": "[Unknown]",
        "_idlePrev": "[Unknown]",
        "_idleStart": "[Unknown]",
        "_events": "[Unknown]",
        "ondata": "[Unknown]",
        "onend": "[Unknown]",
        "_httpMessage": "[Unknown]"
    },
    "connection": "[Unknown]",
    "_events": "[Unknown]",
    "_headers": "[Unknown]",
    "_headerNames": "[Unknown]",
    "_pipeCount": "[Unknown]"
},
"headers": "[Unknown]",
"target": "[Unknown]",
"_pipeCount": "[Unknown]",
"method": "[Unknown]",
"url": "[Unknown]",
"query": "[Unknown]",
"ended": "[Unknown]"
}

我在这里创建了一个小的Node.js模块来做到这一点:https://github.com/ericmuyser/stringy 随时改进/贡献!