shadow
shadow

Reputation: 90

Android call JS from Native Code

I'm trying to call JS functions from Android native code, but they don't seem to be working. I've tried many solutions but to no solution. Here is my code:

public class MainActivity extends Activity {

private WebView webView;

@SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MyCustomWebViewClient());

webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);

webView.loadUrl("http://google.com");

}

private class MyCustomWebViewClient extends WebViewClient {

@Override
public void onPageFinished(WebView view, String url) {
    webView.loadUrl("javascript:alert('shadow');");
    Toast.makeText(getApplicationContext(), "DONE", Toast.LENGTH_LONG).show();

}
} 


} 

Please help.

Thanks

Upvotes: 0

Views: 1121

Answers (1)

mttdbrd
mttdbrd

Reputation: 1831

You can't do alert() with Android's WebView. If you want to show alert dialogs, you need to handle it in your Activity code or use a WebChromeClient. Per the docs:

Creating and setting a WebChromeClient subclass. This class is called when something that might impact a browser UI happens, for instance, progress updates and JavaScript alerts are sent here (see Debugging Tasks).

See: https://developer.android.com/reference/android/webkit/WebView.html

With a WebView you can still write a JavaScript function that sets the value of a textbox to some string. If you need specific code to help you with this, let me know. If you've gotten this far though, you probably can handle it on your own is my guess.

Edit 1

First create a method in JavaScript called sendValueToAndroid()

myWebView.loadUrl("javascript:sendValueToAndroid()");   

In the JavaScript method, call an exposed method in your Android code.

function sendValueToAndroid()
{
    val divValue = ...
    Android.sendValueToAndroid(divValue);
}

Expose a method in the Android app in any object of your choosing.

@JavascriptInterface
public String sendValueToAndroid(String val)
{
    //do something in your app
}

Basically, what you're doing is telling the WebView to invoke a JavaScript method which invokes a callback method in your own app.

Upvotes: 1

Related Questions