Android Webview: javascript execution from java method called from javascript

I have the following javascript code:

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

where AndroidObject is the javascript interface for java. It has a method call

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

The following code will throw an error until the execution of "i is defined" in javascript, since javascript will not be executed in the context from which the Java code was called.

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

"i" is an integer in this example, but can be an object of any type.

Thanks.

+4
source share
2 answers

Suppose I am 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 + ');'); } }); } 
+1
source

I suggest you create a function to get the value of i if your i variable is global, for example:

 var i = 20; function getValueOfI() { return i; } 

and in your java code use something like this:

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

Update If you want to achieve the same result with local variables:

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

where AndroidObject is the javascript interface for java. It has a 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 + ");"); } }); } 
0
source

Source: https://habr.com/ru/post/1438930/


All Articles