Preface: I have a problem doing the project today. When loading a web page, the webView passes a value to the web before rendering it. After that, are you interested? Next, I will summarize the JS interaction in detail. I hope it’s helpful to the students.
Android calls methods on the Web
Go straight to the code:
// Call with no arguments, method name: setDeviceData; The argument here is JSON
binding.webViewX5.loadUrl("javascript:setDeviceData()");
// Call with arguments, method name: setDeviceData; The parameter is JSON
binding.webViewX5.loadUrl("javascript:setDeviceData('" + json + "')");
Copy the code
Web calls to methods on Android
2.1. Step 1:
First we define an inner class in our webView Activity as follows:
- Test () is the method that the webView is calling us
- Note that there are no parameters in the test method. There are several parameters that need to be defined for the web call
@SuppressLint("JavascriptInterface")
private class AndroidJavaScript {
Context mContxt;
public AndroidJavaScript(Context mContxt) {
this.mContxt = mContxt;
}
@JavascriptInterface
public void test(int value) {}}Copy the code
2.2. Step 2:
Then addJavascriptInterface, either before or after loadUrl.
binding.webViewX5.addJavascriptInterface(new AndroidJavaScript(WebMciActivity.this), "android");
binding.webViewX5.loadUrl(url);
Copy the code
That’s it. At this point you might ask where the “Android” came from, so look at the code for the Web front end:
You can see the code for window.android. Yes, if the web is not written for android, then we need to keep it consistent with the web front end when we addJavascriptInterface
How to pass the value to the Web before the webView is loaded?
The problem is this: we need to pass a value to the Web before the webView renders the page. Let’s say we pass a value to testInfo on the Web. If testInfo=1, we turn the switch on, otherwise we turn it off.
After a lot of experimentation, I finally found a way. I don’t have to tell you what the code is
- binding.webViewX5.loadUrl(“javascript:testInfo=1”);
- Note that this code passes a constant 1 to testInfo. To pass a string or JSON bean object, use the following code:
// Remember, after a lot of manual labor, come to the conclusion!!
binding.webViewX5.loadUrl("javascript:var deviceInfo='" + json + "'");
Copy the code
So the question is, where should this code be executed? We all know that webView has two listeners, one of which is:
- setWebChromeClient(webChromeClient);
The load is in this webChromeClient.
private boolean isInit = true;
private WebChromeClient webChromeClient = new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (isInit){
isInit = false;
binding.webViewX5.loadUrl("javascript:testInfo=1"); }}@Override
public void onReceivedTitle(WebView webView, String s) {
super.onReceivedTitle(webView, s); }};Copy the code
Finally, the requirements are solved. If it helps you, you can like it.