view raw
Lord of dark Lord of dark - 7 months ago 152
Android Question

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 ";", how can i do it in my app ?


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();

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(";", null);