unable to execute javascript code in Android WebView from Service

0 votes
asked Sep 12, 2017 by gabe-oleary

I'm attempting to create and Android service that performs a task using JavaScript. I came across this post which describes how to run JavaScript code inside of a WebView within a Service using the WindowManager. I am able to create a WebView with an .html and .js file with no problem. It is once I try to pass data from the android .java service to the WebView that I run into an issue.

I have tried doing so in this fashion:

final WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
...
wv = new WebView(this);
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("file:///android_asset/www/test.html");
windowManager.addView(wv, params); // params set using method from linked post above
wv.evaluateJavascript("console.log('hello');", null);
wv.loadUrl("javascript:console.log('blah')");

Neither the call to evaluateJavascript() nor loadUrl() appear to have any effect on the WebView (I access the console using the chrome developer tools).

I have tested that in test.html I can add a <script> tag and output text to the console with no issue.

I've also tried calling the functions before adding the view to no avail.

2 Answers

0 votes
answered Sep 12, 2017 by a-person

If you're trying to execute this from a Service, you'll need to post a Runnable on the UI thread. Read the doc for evaluateJavascript()

It explicitly says it must be called on the UI thread. I think you can just do:

wv.post(new Runnable(){
        @Override public void run()
        {
            wv.evaluateJavascript();
        }
    });

Other than that, should you include tags?

+1 vote
answered Sep 13, 2017 by oriharel

What kind of data you want to pass to Javascript? You could use the WebView.addJavascriptInterface() to "Plant" methods on the HTML document so you can call them from Javascript, invoke in native and return data back to Javascript. Will that help?

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...