2

have a weird behaviour. In a UIWebView I have a javacript function to detect the postion of an element. this one:

function getPosition(element){

    var el = element;
    var pos = [el.offsetLeft, el.offsetTop];
    var parent = el.offsetParent;
    if (parent != el) {
        while (parent) {
            pos[0] += parent.offsetLeft;
            pos[1] += parent.offsetTop;
            parent = parent.offsetParent;
        }
    }
    //alert(pos);
    return pos;
}

nothing special… but when I call the function like that:

NSString *position = [browserWebView stringByEvaluatingJavaScriptFromString:@"getPosition(document.getElementById('exampleElement'));"];

I get an empty NSString back. When I insert an alert into the function (which is uncomment right now) I get the correct position in the alert!!

Why do I not get the value back and getting just an empty string when the correct return value pos seems to be there?

1 Answer 1

3

This is rather simple and a complete mystery to me at the same time. I don't know why but "stringByEvaluatingJavaScriptFromString:" likes for the javascript result to already resemble a string. To fix your code just add a join() function to your returning array:

return pos.join();

This will join the array into a single string and it will pass as an NSString no problem.

I presume the reason alerts work is that it wouldn't break sites that display data in a similar manner.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, if my answer works, you might want to accept it. That's how stackoverflow works. Read: How does accepting an answer work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.