Some time ago, my company's project involved communication between WebView and JS. So I checked some information on the Internet and studied the problem.
1. Interaction between WebView and JS
1. JS calls local methods
This function is easy to implement. You can directly call the WebView method to add an interface. However, you must start the interaction first.
// Enable javascript mWebView. getSettings (). setJavaScriptEnabled (true); // Add the public void addJavascriptInterface (Object object Object, String name)
Object is the Object of the local class called by JS, and name is the alias of the Object. In JS, you can use this alias + dot syntax + method name to call the local method. For example:
WebView mWebView;// ...mWebview.addJavascriptInterface(this, "myjs");
Define another method that JS can call:
Public void jsFunction (String string) {System. out. println ("js called this method:" + string );}
In this way, this method can be called in JS.
Note: This method cannot be defined as private, or JS cannot be called.
2. Locally call JS Methods
This is easier--simply use the following method. Assume that there is a method called androidFunction () in JS ()
mWebview.loadUrl("javascript:androidFunction()");
Ii. Message Processing
1. An Uncaught ReferenceError occurs :...
This error does not crash. It means that the method called is not found when the local method calls JS. What should we do if the method we call does not exist? Shamoo tried try... catch... to capture the exception and found that nothing was caught... later, I carefully checked the TAG of the error Log, which is the Web Console. Shamoo wanted to find a way to capture this exception. So she looked at the official documentation and finally found this method:
mWebview.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { // TODO Auto-generated method stubif (consoleMessage.message().contains("Uncaught ReferenceError")) {// do something...}return super.onConsoleMessage(consoleMessage); }});
This method can listen to the WebView console message and determine whether the message contains "Uncaught ReferenceError" to capture the message.
2. Get the return value of the JS method
After careful observation, we will find that the loadUrl method of WebView has no returned value. What should we do if we want to obtain the return value of the JS method? Shamoo checked some information and found that there was no good solution on the Internet. Later, it was only possible to implement the return through the callback method. Although it was not flexible, there was no way...
When loadUrl calls a JS method and then JS executes the method, it calls a local Android method and passes the return value as a parameter.