How to stringify event object?
You won't be able to serialize an event object with JSON.stringify, because an event object contains references to DOM nodes, and the DOM has circular references all over the place (e.g. child/parent relationships). JSON can't handle these by default, so you're a bit out of luck there.
I'd suggest to look at How to serialize DOM node to JSON even if there are circular references? which has a few suggestions on how to serialize a DOM node. Also, the following questions seem to have useful information:
- How to save an object with circular references?
- Stringify (convert to JSON) a JavaScript object with circular reference
JSON libraries able to handle circular references seem to be
- JSON-js (see cycle.js)
- dojox.json.ref
Alternatively, you could delete all references to DOM nodes if you don't need them, and then serialize the object. You shouldn't do this after all. See @PointedEars comment :)
Use the "replacer" function to avoid errors:
JSON.stringify(evt, function(k, v) {
if (v instanceof Node) {
return 'Node';
}
if (v instanceof Window) {
return 'Window';
}
return v;
}, ' ');
Update 2019: the browser API has changed some way, here is a method to expose all available keys in Event prototype chain
function stringifyEvent(e) {
const obj = {};
for (let k in e) {
obj[k] = e[k];
}
return JSON.stringify(obj, (k, v) => {
if (v instanceof Node) return 'Node';
if (v instanceof Window) return 'Window';
return v;
}, ' ');
}