I'm trying to get Firefox 13 to turn a geolocation position object into a JSON string, but it's returning an empty string rather than the correct string representation of my JSON object. This is working fine in the latest versions of Chrome and Safari, as well as the Android browser. Here's my code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
//Success handler
console.log(position); //This outputs the position object to the console
var gps = JSON.stringify(position);
console.log(gps); //This outputs an empty string!
},
function (error)
{
//Handle error
},
{ maximumAge: 3000, timeout: 60000, enableHighAccuracy: true }
);
}
else {
//Handle error
}
In Chrome, this outputs a geolocation object, and this string:
"{"coords":{"latitude":XYZ,"heading":null,"accuracy":40,"altitudeAccuracy":null,"altitude":null,"longitude":XYZ,"speed":null},"timestamp":1339712284200}"
However, in Firefox 13 the output is just an empty string, even though the geolocation object that's printed to the console is to all intents and purposes the same as the object displayed by Chrome. Any ideas on what's going wrong here? This seems to be a related issue, but I don't see a solution there either. IE9 displays the same behaviour, by the way.
What's going on is that JSON.stringify only looks at the object's own properties by default.
And per DOM specs all DOM properties actually live on the object's prototype.
IE and Firefox implement the spec correctly by putting the properties on the prototype. Chrome and Safari do not: they put the properties directly on the object. That makes this case work, but breaks other things (e.g. the ability to hook the property getters and setters)....
There's talk of adding toJSON methods to some DOM objects to give them more reasonable behavior for JSON.stringify.