Alexander Ponomarev
Alexander Ponomarev

Reputation: 91

Android Webview: Execution of javascript from java method called from javascript

I have the following javascript code:

    function mine()
    {
        var i = 3;
        AndroidObject.call();
    }

where AndroidObject is javascript interface to java. It has method call

    WebView myWebView;

    public void call()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                myWebView.loadUrl('javascript:alert(i);');
            }
        });
    }

The following code will produce error while execution " i is not defined " in javascript, since javascript will be executed not in the context where java code was called from.

Is it possible to execute JS from java method in the same context, i.e. to make "i" visible in the case above?

"i" is integer in this example, but it may be object of ANY type.

Thanks.

Upvotes: 4

Views: 1944

Answers (2)

Kiran
Kiran

Reputation: 191

Suppose i is an integer,

function mine()

 {

var i = 3;

AndroidObject.call(i);

}

and

WebView myWebView;

public void call(Integer i)
{
Integer temp = i;
    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            myWebView.loadUrl('javascript:alert(' + temp + ');');
        }
    });
}

Upvotes: 1

Mohsen Afshin
Mohsen Afshin

Reputation: 13436

I suggest you to create a function to get value of i if your i variable is global, like this:

var i = 20;

function getValueOfI() {
     return i;
}

and in your java code use something like this:

 myWebView.loadUrl('javascript:alert(getValueOfI());');

Updated If you want to achieve the same with local variables:

 function mine()
    {
        var i = 3;
        AndroidObject.call(i);
    }

where AndroidObject is javascript interface to java. It has method call

WebView myWebView;

public void call(final Integer i)
{
    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            myWebView.loadUrl("javascript:alert(" + i + ");");
        }
    });
}

public void call(final String i)
{
    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            myWebView.loadUrl("javascript:alert(" + i + ");");
        }
    });
}

public void call(final Boolean i)
{
    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            myWebView.loadUrl("javascript:alert(" + i + ");");
        }
    });
}

Upvotes: 0

Related Questions