Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Use WebView to evaluate a javascript string and return the value

Given that scripting is not natively supported in Android and wrapping libraries like javax.script.ScriptEngine into your app will make it too large, is it possible to send a javascript string to an invisible WebView and have it evaluate the string and return you the results (another string)?

I want to go this route because I want to save all my scripts to disk so my app can remain small.

Edit

I need Java code to evaluate javascript strings not the other way around. addJavascriptInterface() doesn't help.

like image 367
Tawani Avatar asked Dec 01 '09 15:12

Tawani


People also ask

Can WebView run JavaScript?

Enable JavaScriptYou can enable it through the WebSettings attached to your WebView . You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() . WebView myWebView = (WebView) findViewById(R. id.

How do I get messages from WebView?

HTML, CSS and JavaScript for Android WebView Depending on your requirements, you can fetch the contents of the WebView from the web using webView. loadUrl("<url>") method, or you can bind the code directly (e.g. after loading it from assets) using webView. loadDataWithBaseURL("", html, "text/html", "UTF-8", null) .

What can I use instead of WebView?

Alternatives to WebView If you want to send users to a mobile site, build a progressive web app (PWA). If you want to display third-party web content, send an intent to installed web browsers. If you want to avoid leaving your app to open the browser, or if you want to customize the browser's UI, use Custom Tabs.

How do I print from WebView?

You can also load a web page for printing by replacing the loadDataWithBaseURL() method with loadUrl() as shown below. // Print an existing web page (remember to request INTERNET permission!): webView. loadUrl("https://developer.android.com/about/index.html");


1 Answers

Can it be done? Yes, via addJavascriptInterface() and sending the browser a javascript: URL, akin to a bookmarklet.

A far simpler answer, one that will use much less memory and will execute much faster, is to not use Javascript.

like image 75
CommonsWare Avatar answered Sep 17 '22 14:09

CommonsWare