How to call javascript function directly from activity in Android?

I wanted to know if there is a way that I can call a JavaScript function from my own Android activity.

I came across:

webView.loadUrl("javascript:hello()"); 

But that did not work for me.

Also, how does Android know which html page this JavaScript function is on?

+8
javascript android
source share
3 answers

Android can only call javascript if the html page loads in webView

 webView.loadUrl("javascript:hello()"); 

will call the hello writen method on the html page only if the page containing this method is currently loading in the webview control

first call

 webview.loadUrl("Your html page url"); 

then call

 webView.loadUrl("javascript:hello()"); 
+13
source share

If someone has problems with this, like me, you need to call the javascript function after the page has finished loading, otherwise javascript will not be called:

  webviewer.loadUrl("file:///android_asset/mypage.html"); webviewer.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { webviewer.loadUrl("javascript:hello()"); } }); 
+10
source share

Before using JavaScript, you must first check whether Javascript is enabled or not in your application using "getJavaScriptEnabled ()" (defaults to FALSE). And the loadUrl () method is only used to load the current page. Its action is not related to JavaScript.

Example:

WebView Setup

// initialize webview

 webView = (WebView) findViewById(R.id.webView); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); 

HTML loading in WebView

 webView.loadUrl("file:///android_asset/testhtml.html"); 

Setting up WebChromeClient on webView

 webView.setWebChromeClient(new MyJavaScriptChromeClient()); 

Class MyJavaScriptChromeClient Here we must override the onJsAlert () method to handle the JavaScript alert function.

 private class MyJavaScriptChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message,final JsResult result) { //handle Alert event, here we are showing AlertDialog new AlertDialog.Builder(MainWebViewActivity.this) .setTitle("JavaScript Alert !") .setMessage(message) .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do your stuff result.confirm(); } }).setCancelable(false).create().show(); return true; } } 

My html file is: testhtml.html:

 <html> <body > <div onclick="alert('hello')"> Click Me !! </div> </body> </html> 

How it works? When the text "Click Me !!" the android onJsAlert function is called on the WebView screen (WebView view, string URL, String message, final result of JsResult). The notification parameter is copied to the message parameter of the onJsAlert function. And the rest of the processing is done there. Here we show the AlertDialog.

+3
source share

All Articles