Search code examples
javajavascriptjsongoogle-chromestringify

JSON Stringify returns null, but document.write prints out properly


I'm trying to write a plugin for crawljax that runs some javascript code, like this:

String result = browser.executeJavaScript(script).toString();

and the script code:

function getElementPosition(id) {
var element = document.getElementById(id);
return JSON.stringify(elementpos(findPosX(element), findPosY(element)));
}

function elementpos(x, y) {
elementpos = new Object();
elementpos.x = x;
elementpos.y = y;
return elementpos;
}


return getElementPosition("foo");

This returns successfully, but the result always is null, even though if I print out the same thing using document.write, I get a nicely formatted JSON string

{"x":8, "y":24}

Am I misunderstanding something? Is there some weird thing that happens with JSON strings and java? I don't have a lot of experience in javascript, so am I not allowed to just return like that?

I'm testing this out on google chrome, v. 25

Note: I don't think it's got anything to do with Crawljax itself, as theres a separate plugin (written by someone else), which also has a script that returns a JSON string, but that seems to work perfectly fine...


Solution

  • JavaScript is allergic to new Object(); do a shortcut, try the one below, that may solve;

     return JSON.stringify({x:findPosX(element), y:findPosY(element)});
    

    Objects created with new Object(); syntax brings many weird problems in javascript.