Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON.stringify only show the isTrusted member of a click event?

HTML:

<button onclick="foo(event);">Test</button>

Javascript:

window.foo = function(event) {
  console.log(JSON.stringify(event));
}

Console Result:

{"isTrusted":true}

It is happening on Chrome. I haven't tested other browsers yet.

like image 695
Sanford Staab Avatar asked Dec 07 '16 14:12

Sanford Staab


1 Answers

There are a number of reasons why some properties do not get included in JSON.stringify:

  1. They might be functions, which cannot be stringified
  2. They might belong to the prototype (i.e. class) of an object, rather than directly belonging to the object itself.

If you need to include extra data, your best bet is to manually construct a fresh object with the things you want to include:

window.foo = function(event) {
  console.log(JSON.stringify({keyCode: event.keyCode));
}
like image 103
ForbesLindesay Avatar answered Sep 18 '22 02:09

ForbesLindesay