0

Is it possible to execute an arbitrary JavaScript function against a WebView-loaded URL?

For example:

WebView vhrWebView = this.findById(R.id.vhr_web_view);
vhrWebView.getSettings().setJavaScriptEnabled(true);

vhrWebView.setWebChromeClient(new WebChromeClient());
vhrWebView.evaluateJavascript("function() {alert('It works!');}();", null);

vhrWebView.loadUrl("http://www.google.com");

I realize that the example does not make a lot of sense but what I would like to do is auto-populate a web-page (that I don't control) with credentials I do have through Javascript. However, I cannot seem to get even the most basic JavaScript to function with the URL loaded and this was the best example I could come up with: popping up a JavaScript dialog box when the Google website is loaded within a WebView.

Is what I want to do possible?

1
  • Try doing something else, or check LogCat. If you are expecting alert() to have an impact beyond logging to LogCat, you will need to have your own real actual honest-to-goodness WebChromeClient subclass, overriding onJsAlert(), rather than the do-nothing implementation that you have now. Or, test using something else, like modifying the DOM. Also, bear in mind that you may not be able to evaluate any JavaScript until the page is loaded, and you certainly cannot modify the DOM of a page until it is loaded. Commented Dec 10, 2014 at 16:27

1 Answer 1

1

You need to wait for the page to finish loading before you can issue JS calls. Try moving your evaluateJavascript call to WebViewClient.onPageFinished.

Sign up to request clarification or add additional context in comments.

1 Comment

That was it. I thought the evaluateJavascript method appended the JavaScript to the end on page load, rather than explicitly having to indicate that using onPageFinished

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.