Run javascript without webview in Android

I am trying to execute JS-fonction in my android app. The function is located in the .js file on the website.

I do not use webview, I want to execute a JS function because it sends the request that I want.

In the console in my browser, I just need to do question.vote(0); How can I do this in my application?

+5
source share
2 answers

You can execute JavaScript without a WebView. You can use AndroidJSCore . Here is a brief example of how you can do this:

 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 will not work outside of WebView, because I suppose you not only rely on JavaScript, but also on AJAX, which is not part of pure JavaScript. This requires a browser implementation.

Is there a reason you are not using hidden WebView and just entering your code?

 // Create a WebView and load a page that includes your JS file webView.evaluateJavascript("question.vote(0);", null); 
+5
source

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

This library is a wrapper for Duktape , a built-in JavaScript engine.
You can run javascript without participating in a WebView.

Duktape is compatible with Ecmascript E5 / E5.1, so basic things can be done with it.

+6
source

Source: https://habr.com/ru/post/1215492/


All Articles