Why console.log(window) works but JSON.stringify(window) doesn't work, and how can I beat that?

StackOverflow https://stackoverflow.com/questions/21556185

  •  06-10-2022
  •  | 
  •  

Question

If I type in console:

 console.log(window)

I get all the objects in window with expand buttons.

But if I try the same with:

JSON.stringify(window) 

I get in Firefox:

Error: Permission denied to access property 'toJSON'

And in chrome:

TypeError: Converting circular structure to JSON

Is this the only case where this happen? And given that console.log() and JSON.stringify() work differently, can I access and still stringify objects that console.log() manages to display?

Was it helpful?

Solution

That's because window has circular references (for instance, in most cases window.self refers to window) and then it cannot be converted to JSON, otherwise it would turn into an infinite loop.

This may happen on any object, not only on window:

var foo = {
    bar: 'bar'
};
JSON.stringify(foo);    // works fine

var foo = {
    bar: foo
};
JSON.stringify(foo);    // circular reference -> crashes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top