Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript from Android?

How do we call javascript from Android? I have this javascript library which I would like to use, I want to call the javascript function and pass the result value to the android java code. Haven't found the answer from now. i managed to call android code from javascript, but I want the other way around.

like image 809
phoenix Avatar asked Sep 25 '11 09:09

phoenix


People also ask

Can I run JavaScript on Android?

We can execute Js function using Android. But only logic code. We cannot do any UI changes kind of things(as I know) using this libraries. The library which we are using to execute JS is Rhino.

Can WebView run JavaScript?

WebView is a special component in Android which serves as kind of built-in browser inside Android applications. If you want to execute HTML, CSS or JavaScript code in your Android app, or you need to allow users visit a URL without leaving your application, WebView is the way to go.

How do I enable JavaScript on Android WebView?

JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView . You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() . WebView myWebView = (WebView) findViewById(R.

How do you communicate between WebView and native Android?

2.1 To receive data from webview ,we can create an interface, which will enable webview to connect the native layer and pass data. From native layer, create a class and replicate the following. While configuring web view, we need to set JavaScript interface as above JSBridge class.


1 Answers

There is a hack:

  1. Bind some Java object so that it can be called from Javascript with WebView:

    addJavascriptInterface(javaObjectCallback, "JavaCallback")
    
  2. Force execute javascript within an existing page by

    WebView.loadUrl("javascript: var result = window.YourJSLibrary.callSomeFunction();
        window.JavaCallback.returnResult(result)");
    

(in this case your java class JavaObjectCallback should have a method returnResult(..))

Note: this is a security risk - any JS code in this web page could access/call your binded Java object. Best to pass some one-time cookies to loadUrl() and pass them back your Java object to check that it's your code making the call.

like image 132
Peter Knego Avatar answered Sep 26 '22 01:09

Peter Knego