13

I'm trying to execute a JS fonction in my Android app. The function is in a .js file on a website.

I'm not using webview, I want to execute the JS function because it sends the request i want.

In the Console in my browser i just have to do question.vote(0);, how can I do it in my app ?

Fabich
  • 2,768
  • 3
  • 30
  • 44

2 Answers2

10

UPDATE 2018: AndroidJSCore has been superseded by LiquidCore, which is based on V8. Not only does it include the V8 engine, but all of Node.js is available as well.

You can execute JavaScript without a WebView. You can use AndroidJSCore. Here is a quick example how you might do it:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://your_website_here/file.js");
HttpResponse response = client.execute(request);
String js = EntityUtils.toString(response.getEntity());

JSContext context = new JSContext();
context.evaluateScript(js);
context.evaluateScript("question.vote(0);");

However, this most likely won't work outside of a WebView, because I presume you are not only relying on JavaScript, but AJAX, which is not part of pure JavaScript. It requires a browser implementation.

Is there a reason you don't use a hidden WebView and simply inject your code?

// Create a WebView and load a page that includes your JS file
webView.evaluateJavascript("question.vote(0);", null);     
Eric Lange
  • 1,755
  • 2
  • 19
  • 25
  • Excellent idea, Eric. An answer to your last question from 2023: one reason not to use a webview is that it only works for 5 minutes in the background in Android 13 (and a few lower also). So your answer is helpful for me. – Luis A. Florit Jul 13 '23 at 11:42
6

For the future reference, there is a library by square for this purpose. https://github.com/square/duktape-android

This library is a wrapper for Duktape, embeddable JavaScript engine.
You can run javascript without toying with WebView.

Duktape is Ecmascript E5/E5.1 compliant, so basic stuff can be done with this.

yshrsmz
  • 1,179
  • 2
  • 15
  • 33
  • 2
    What are the benefits of duktape-android compaired to LiquidCore (previously known as AndroidJSCore)? – Roel Feb 22 '17 at 10:37