Those who have done hybrid development of Android should know how to interact with Java code and Javascript code in Android.
First, let’s review the interaction between Java and Javascript.
JavaScript calls Java
Add Java methods for Html page calls in WebView in Android:
(new DirectToJS(), "AndroidObj"); class DirectToJS{ @JavascriptInterface public void showToast(){ (this, "Android Toast",Toast.LENGTH_SHORT).show(); } }
The way JavaScript calls Java methods in the Html page is as follows:
();
In the JavaScript code: window is the Window entity of a web page, which is very familiar to people who do front-end development; AndroidObj is an entity provided by the Android side to the WebView, and Android will assign this entity to the window of the WebView; showToast() is the method provided by Java to Html.
Java Call JavaScript
First, write an ordinary JavaScript method on Html:
function showAlert(){ alert("Html Alert"); }
In Android, just execute the following code:
("javascript:showAlert()");
The pit on the Vue framework
If the front-end uses the Vue framework, then if you write a method directly on the js script, Android will not be called, no matter where it is written.
This is because in the Vue framework, the methods on the script are not methods that belong to window. You should assign the methods to be called to Android to window, so that you can get the following in Android:
window['showAlert'] = { alert("Html Alert"); }
In short, for ordinary web pages, methods written on js scripts belong to window entities by default; while in the Vue framework, because the implementation mechanism inside the framework is quite special, the methods you wrote on js scripts are not methods on the real page, so they cannot be called in Android.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.