Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript without webview in Android

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 ?

like image 798
Fabich Avatar asked Mar 17 '15 01:03

Fabich


2 Answers

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);     
like image 118
Eric Lange Avatar answered Sep 28 '22 02:09

Eric Lange


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.

like image 40
yshrsmz Avatar answered Sep 28 '22 04:09

yshrsmz