0

I'm calling a JavaScript function from my application's WebView. This function returns (if i call it from firebug) for example:

Object {top: 350.171875, left: 129.265625, w: 311, h: 115}

What i want is to get the values of top, left, w and h from my Android application. But when I try to get the values through WebChromeClient onJsAlert() method the value of message parameter is [object Object]. Is there a way to extract the required values of top, left, w, h from [object Object]? i can't find a way to parse [object Object].

3
  • 1
    you need to bind a javascriptinterface to your webview Commented Sep 5, 2013 at 8:39
  • Isn't enough something like that? myWebView.loadUrl("javascript:someJsFunction()"); Commented Sep 5, 2013 at 9:50
  • this will call the javascript function, but you will not be able to get the return value of the function. You need a callback in java with a javascriptinterface. Commented Sep 5, 2013 at 10:12

2 Answers 2

1

Typically, you can use a JavascriptInterface (see http://developer.android.com/guide/webapps/webview.html).

This can be your callback interface:

public class MyInterface {
    @JavascriptInterface
    public void myCallback(int top, int left, int w, int h) {
        // This is where you receive the values
    }
}

This is how you bind it:

myWebView.addJavascriptInterface(new MyInterface(), "Android");
myWebView.loadUrl("javascript:someJsFunction()");

And this is is how you javascript sends the values :

function someJsFunction() {
    Android.myCallback(dimensions.top, dimensions.left, dimensions.w, dimensions.h);
}

You cannot pass an actual object from javascript to android. You can only pass primitives, strings, and arrays of these.

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

2 Comments

So, if someone has no access to the javascript function to edit it and add as a return value Android.myCallback(...), there is no other way to pass the javascript object to Android.
you can use an eval to pass new javascript to the currently executed : javascript:eval('Android:myCallback(...)')
1

You should be able to simply do dimensions.top or dimensions.left, etc (Assuming the object is stored in the variable dimensions)

var dimensions = {top: 350.171875, left: 129.265625, w: 311, h: 115}; //Would actually be a call to your function to calculate these dimensions
alert(dimensions.top);

Comments

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.