Skip to content Skip to sidebar Skip to footer

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 req

Solution 1:

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:

HttpClientclient=newDefaultHttpClient();
HttpGetrequest=newHttpGet("http://your_website_here/file.js");
HttpResponseresponse= client.execute(request);
Stringjs= EntityUtils.toString(response.getEntity());

JSContextcontext=newJSContext();
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);     

Solution 2:

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.

Post a Comment for "Execute Javascript Without Webview In Android"