I've got the following...
chrome.extension.sendRequest({
req: "getDocument",
docu: pagedoc,
name: 'name'
}, function(response){
var efjs = response.reply;
});
which calls the following..
case "getBrowserForDocumentAttribute":
alert("ZOMG HERE");
sendResponse({
reply: getBrowserForDocumentAttribute(request.docu,request.name)
});
break;
However, my code never reaches "ZOMG HERE" but rather throws the following error while running chrome.extension.sendRequest
Uncaught TypeError: Converting circular structure to JSON
chromeHidden.JSON.stringify
chrome.Port.postMessage
chrome.initExtension.chrome.extension.sendRequest
suggestQuery
Does anyone have any idea what is causing this?
It means that the object you pass in the request (I guess it is
pagedoc
) has a circular reference, something like:JSON.stringify
cannot convert structures like this.N.B.: This would be the case with DOM nodes, which have circular references, even if they are not attached to the DOM tree. Each node has an
ownerDocument
which refers todocument
in most cases.document
has a reference to the DOM tree at least throughdocument.body
anddocument.body.ownerDocument
refers back todocument
again, which is only one of multiple circular references in the DOM tree.Based on zainengineer's answer... Another approach is to make a deep copy of the object and strip circular references and stringify the result.
I normally use the circular-json npm package to solve this.
https://www.npmjs.com/package/circular-json
As per the JSON docs at Mozilla,
JSON.Stringify
has a second parametercensor
which can be used to filter/ignore children items while parsing the tree. However, perhaps you can avoid the circular references.In Node.js we cannot. So we can do something like this:
The result:
Unfortunately there seems to be a maximum of 30 iterations before it automatically assumes it's circular. Otherwise, this should work. I even used
areEquivalent
from here, butJSON.Stringify
still throws the exception after 30 iterations. Still, it's good enough to get a decent representation of the object at a top level, if you really need it. Perhaps somebody can improve upon this though? In Node.js for an HTTP request object, I'm getting:I created a small Node.js module to do this here: https://github.com/ericmuyser/stringy Feel free to improve/contribute!
This might not be related answer, but this link Detecting and fixing circular references in JavaScript might helpful to detect objects which are causing circular dependency.
I have experienced the same error when trying to build the message below with jQuery. The circular reference happens when
reviewerName
was being mistakenly assigned tomsg.detail.reviewerName
. JQuery's .val() fixed the issue, see last line.