11

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.

Sanford Staab
  • 239
  • 2
  • 10
  • //jsfiddle.net/sanfords/djf2nxwd - this is the fiddle I tried to embed in the original post. – Sanford Staab Dec 07 '16 at 14:42
  • 2
    Possible duplicate of [How to stringify event object?](http://stackoverflow.com/questions/11547672/how-to-stringify-event-object) – Mahi Dec 07 '16 at 14:46
  • No I take that back. It IS a dupe. – Sanford Staab Dec 07 '16 at 14:50
  • I dont' think either of the two answers actually answers the question! I have the same issue: when I pass "event" into javascript function from onclick= there are no other properties attached to the event except isTrusted... where are all the other properties (like keyCode)? It really has nothing to do with JSON.stringify ... no other properties seem to exists at all. – jsherk Jun 02 '20 at 02:59

2 Answers2

5

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));
}
ForbesLindesay
  • 10,482
  • 3
  • 47
  • 74
  • I think there is error in this code: there is one opening {curly brace in front of keyCode but I do not see a closing curly brace. – jsherk Jun 02 '20 at 03:04
2

The event itself is full of prototype functions - which are getting hidden by stringify (as ForbesLindesay already pointed out).

Otherwise it's not common to see onclick in HTML markup (since it generates very tight dependencies with your code).

Most browsers (beyond IE7) also allow you unpacking of values inside the console - which you can see here: http://jsfiddle.net/djf2nxwd/14/

document.getElementById('foo').onclick = (event) => {
    console.log(JSON.stringify(event));
    console.log(event);
};

That's probably the behaviour you expected.

Mio Bambino
  • 544
  • 3
  • 15