Question

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...

Was it helpful?

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.

OTHER TIPS

I don't think the problem here is with new Object(), but commenters please feel free to fill me in if I am wrong on that point. Try this:

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

Notice that I have put "var" in front of "elementpos = new Object();". Without that variable definition the first line of the global "elementpos" function is to replace itself with an "elementpos" object. The first time it executes will probably be OK, but the second time will likely fail with an exception as it tries to treat the new Object() result as a function to call.

I was able to execute the code above and stringify the result without any problems under chrome 40. Note also that calling the local variable "result" or something other than the function name would remove some potential confusion here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top