Unable to convert JavaScript window.screen object into string

Viewed 992
  • I want to convert the window.screen attributes and values into a string to send to the back-end. (I could extract the values for each attribute but curious to understand why the below fails)

  • Not sure why JSON.stringify(window.screen) returns "{}".

  • Note that the manually created object orientation_ appears to convert JSON to string fine.

Google Chrome Console-1


  • Experimenting further, I tried copying the object and then deleting the __proto__ object thinking this might be failing the conversion to string. But strangely I am unable to delete any of the keys!

Google Chrome console-2


Update #1:

  1. Based on below tips that circular reference could be the issue... Console-3 Here we see that variable a has a circular reference to itself. Using Flatted(circular JSON parser) we see a gets converted into String but window.screen still doesn't convert.

  2. Based on the docs JSON.stringify(), functions are stringified as null.So functions are not the problem.

console-6

So still not clear on the reason for this behavior.

1 Answers

The JSON.stringify requires object properties to be stringifiable. At first sight unfolding __proto__ part of window.screen on console dump one can notice that each of listed attribute is in fact getter function (like get availHeight: ƒ availHeight()) and produce result as usual. However Object.keys(window.screen) produces empty array that suggests all properties are not enumerable so they cannot be found introspecting object, also by JSON.stringify. In contrast your orientation object that you stringified has regular properties that by default are enumerable.

Simplest way to stringify window.screen, an object with short number of attributes, is to make its copy that call getter each time, and then stringify copy:

var scr = {
    width: window.screen.width,
    height: window.screen.height //... }
JSON.stringify(scr); // --> "{"width":1600,"height":900, ...
Related