最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Execute javascript without webview in Android - Stack Overflow

programmeradmin1浏览0评论

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 ?

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 ?

Share Improve this question edited Dec 29, 2016 at 22:13 Fabich asked Mar 17, 2015 at 1:09 FabichFabich 3,0694 gold badges32 silver badges46 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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);     

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.

发布评论

评论列表(0)

  1. 暂无评论