I create a page to diagnose the problem that our users encounter with our web pages (you know, asking the user, βWhich browser do you use?β Usually leads to the Internet).
This page is already sending me all the HTTP headers, and now I'm trying to have JavaScript provide additional information, so I thought it would be great to have a custom JavaScript navigator object, and I started to look at how to serialize so I can submit it through the form.
The problem is that I cannot serialize the navigator object using any JSON library that I know of, everyone returns an empty object (?!), So I decided to write an ad-hoc serializer.
The code can be found here:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> function serialize (object) { var type = typeof object; if (object === null) { return '"nullValue"'; } if (type == 'string' || type === 'number' || type === 'boolean') { return '"' + object + '"'; } else if (type === 'function') { return '"functionValue"'; } else if (type === 'object') { var output = '{'; for (var item in object) { if (item !== 'enabledPlugin') { output += '"' + item + '":' + serialize(object[item]) + ','; } } return output.replace(/\,$/, '') + '}'; } else if (type === 'undefined') { return '"undefinedError"'; } else { return '"unknownTypeError"'; } }; $(document).ready(function () { $('#navigator').text(serialize(navigator)); }); </script> <style type="text/css"> #navigator { font-family: monospaced; } </style> <title>Serialize</title> </head> <body> <h1>Serialize</h1> <p id="navigator"></p> </body> </html>
This code works fine in Firefox, Opera, Chrome and Safari, but (obviously) does not work in Internet Explorer (at least version 8.0), it complains that the "Property or method not supported by the object" line for (var item in object) { .
Do you have any hint on how to fix the code or how to achieve the goal (serialize the navigator object) in other ways?
Solution (v 2.0):
Replace
for (var item in object) { if (item !== 'enabledPlugin') { output += '"' + item + '":' + serialize(object[item]) + ','; } }
from
for (var item in object) { try { if (item !== 'enabledPlugin') { output += '"' + item + '":' + serialize(object[item]) + ','; } } catch (e) { } }
and it works.
javascript serialization
Albireo
source share