Full analysis of using WebView to interact with JS in Android

1. Overview

First of all, we need to put forward a concept, that is hybrid, which mainly means the mixed development of native Android and h5. Why do we do this? You can imagine that for the same activity, if a pure native development method is used, both Android and iOS must maintain the same set of interfaces and even logic. In this way, the cost of development and maintenance will be very high. However, if a hybrid development method is used, Let the front-end students write a set of interfaces and logic. For the native side, just use the corresponding container to display it (for Android, this container is of course WebView). So why aren’t all pages developed this way? Because the user experience when using h5 to display the interface is always inferior to native, we need to make a trade-off between the two.

After introducing what hybrid is, let’s consider the following scenarios: Scenario 1: There is a button on the front-end page. Clicking this button needs to display a native component (such as a toast), or clicking this button needs to go to the native side. Perform a time-consuming task. Scenario 2: There is still a button on the front-end page. The logic of clicking this button is: if you are logged in, you will jump to the corresponding interface. If you are not logged in, you will jump to the login interface. This login interface is maintained natively by us. After reading the above two scenarios, I believe everyone has also discovered a problem. There is a problem that needs to be solved in a development method such as hybrid, and that is the communication between the front end and the local. The following will introduce to you the communication method between active native Android and h5.

2. How to use WebView

Using the WebView control is the same as using other controls. Use a “WebView” label in the layout. WebView does not include complete browser functions such as navigation bar and address bar. It is only used to display a web page. To load a web page in WebView, use loadUrl()

Write picture description here

Write picture description here

Pay attention to adding permission to access the Internet in the manifest file:

1. <uses-permission android:name="android.permission.INTERNET"/>

However, when clicking a link in Android, the default is to call the browser program installed on the phone to start it. Therefore, if you want to handle this action through WebView, you need to use WebViewClient

Write picture description here

Write picture description here

Of course, we can also write a class that inherits WebViewClient to extend the WebViewClient object.

Write picture description here

Write picture description here

Then you only need to modify the content of setWebViewClient

Write picture description here

Write picture description here

In addition, due to user habits, WebView needs to behave more like a browser, that is, it needs to be able to roll back the history, so it is necessary to override the system’s back key goBack and goForward to browse the history page forward and backward.

Write picture description here

Write picture description here

Example 1: Use of WebViewClient Layout code activity_main.xml:

1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context="com.example.hybirddemo.MainActivity" >
10.
11. <WebView
12. android:layout_width="match_parent"
13. android:layout_height="match_parent"
14. android:id="@ + id/webView" />
15.
16. </RelativeLayout>

MainActivity code:

 public class MainActivity extends Activity {<!-- -->
2.  
3. private WebView webView;
4.
5. @Override
6. protected void onCreate(Bundle savedInstanceState) {<!-- -->
7. super.onCreate(savedInstanceState);
8. setContentView(R.layout.activity_main);
9.          
10. // Get the webview control
11. webView = (WebView) findViewById(R.id.webView);
12. //Set WebViewClient
13. /*webView.setWebViewClient(new MyWebViewClient());*/
14. //Load the page using webview
15. webView.loadUrl("http://www.baidu.com");
16.
17. webView.setWebViewClient(new WebViewClient() {<!-- -->
18.
19. @Override
20. public boolean shouldOverrideUrlLoading(WebView view, String url) {<!-- -->
21. view.loadUrl(url);
22. return true;
twenty three.             }
twenty four. 
25. @Override
26. public void onPageStarted(WebView view, String url, Bitmap favicon) {<!-- -->
27. // TODO Auto-generated method stub
28. super.onPageStarted(view, url, favicon);
29. }
30.
31. @Override
32. public void onPageFinished(WebView view, String url) {<!-- -->
33. // TODO Aut (view, url);
34. }
35.
36. });
37.
38. }
39.
40. @Override
41. //Override the system’s back key
42. public boolean onKeyDown(int keyCode, KeyEvent event) {<!-- -->
43. if (keyCode == KeyEvent.KEYCODE_BACK & amp; & amp; webView.canGoBack()) {<!-- -->
44. webView.goBack();
45. return true;
46. }
47.
48. return super.onKeyDown(keyCode, event);
49. }
50.
51. }

3. Mutual calls between JavaScript and java

WebSetting is very useful. Through WebSetting, you can use Android’s native JavascriptInterface to communicate between js and java. Example 2: Mutual calls between JavaScript and java

First we write a piece of html code:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>MyHtml.html</title>
5.
6. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
7. <meta http-equiv="description" content="this is my page">
8. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
9.      
10. <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
11. <script type="text/javascript">
12. function showToast(toast) {<!-- -->
13. javascript:control.showToast(toast);
14. }
15. function log(msg) {<!-- -->
16. console.log(msg);
17. }
18. </script>
19. </head>
20.
21. <body>
22. <input type="button" value="toast" onclick="showToast('hello world!')">
23. </body>
24. </html>

This is a very simple html5 page with a button in it. Clicking this button will execute the showToast method in the js script.

Write picture description here

So what does this showToast method do?

Write picture description here

You can see control.showToast. We will talk about what this is later. Let’s look at the java code in our Android project.

Write the layout file activity_main.xml The content of the layout is very simple, it is to nest a WebView control

Write picture description here

Write picture description here

Write MainActivity.java code

1. package com.example.hybirddemo;
2.  
3. import android.annotation.SuppressLint;
4. import android.app.Activity;
5. import android.os.Bundle;
6. import android.util.Log;
7. import android.view.Menu;
8. import android.view.MenuItem;
9. import android.webkit.JavascriptInterface;
10. import android.webkit.WebSettings;
11. import android.webkit.WebView;
12. import android.widget.Toast;
13.
14. public class MainActivity extends Activity {<!-- -->
15.
16. private WebView webView;
17.
18. @Override
19. protected void onCreate(Bundle savedInstanceState) {<!-- -->
20. super.onCreate(savedInstanceState);
21. setContentView(R.layout.activity_main);
22. // Get the webview control
23. webView = (WebView) findViewById(R.id.webView);
24. // Get WebView settings
25. WebSettings webSettings = webView.getSettings();
26. // Set JavaScript to be available. This sentence is necessary, otherwise everything you do will be in vain.
27. webSettings.setJavaScriptEnabled(true);
28. //Add JavaScript interface to webview
29. webView.addJavascriptInterface(new JsInterface(), "control");
30. //Load html page through webview
31. webView.loadUrl("file:///android_asset/MyHtml.html");
32.
33. }
34. public class JsInterface{<!-- -->
35. @JavascriptInterface
36. public void showToast(String toast) {<!-- -->
37. Toast.makeText(MainActivity.this,toast, Toast.LENGTH_SHORT).show();
38. Log.d("html", "show toast success");
39. }
40. public void log(final String msg) {<!-- -->
41. webView.post(new Runnable() {<!-- -->
42.
43. @Override
44. public void run() {<!-- -->
45. webView.loadUrl("javascript log(" + "'" + msg + "'" + ")");
46.
47. }
48. });
49. }
50. }
51. }

The above code mainly does the following steps: a) Get the webview control b) Get the webview settings, set JavaScript to available, and open the JavaScript channel

Write picture description here

Write picture description here

c) Establish an interface in the Android program and write relevant logic. Look at the showToast() method in the previous js script.

Write picture description here

Write picture description here

The control here is our interface, which calls the showToast method of the interface. Obviously, js calls the Android code and outputs a Toast.

Write picture description here

You can see that we named this interface control, and finally loaded the page through loadUrl.

Write picture description here

You can see that a toast is displayed first, and then the log() method is called. The log() method calls the log() method of the js script. What the js log() method does is to output msg on the console. This is obviously Android The js method is called.

Write picture description here

d) Add our own JavaScript interface to the webview. Use the addJavascriptInterface method of WebView to inject an interface we wrote ourselves.

Write picture description here

e) Use the webview control to load the html file we wrote before

Write picture description here

Run the program on a real phone and successfully output the following content on the console:

Write picture description here

In this way, we have completed the intermodulation between js and java. Isn’t it very simple?

4. Handling JS warnings, dialog boxes, etc. in Android

To handle JS warnings, dialog boxes, etc. in Android, you need to set the WebChromeClient object for WebView, and override the onJsAlert, onJsConfirm, and onJsPrompt methods to handle common dialog boxes in javascriptExample 3: Handling javascript dialog boxes in Android< /strong> 1) Write html page layout

1. <%@LANGUAGE="JAVASCRIPT" CODEPAGE="936"%>
2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3. <html xmlns="http://www.w3.org/1999/xhtml">
4. <head>
5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8 " />
6. <title>Test three dialog boxes of javascript respectively</title>
7. <script language="javascript">
8. function ale()
9. {<!-- -->
10. alert("This is a warning dialog box!");
11. }
12. function firm()
13. {<!-- -->
14. if(confirm("For more information, please go to my blog?"))
15. {<!-- -->
16. location.href="http://yarin.javaeye.com";
17. }
18.else
19. {<!-- -->
20. alert("You chose not to go!");
twenty one.     }
twenty two. }
23. function prom()
24. {<!-- -->
25. var str=prompt("Demonstrate a dialog box with input","Enter your information here");
26. if(str)
27. {<!-- -->
28. alert("Thank you for using, what you entered is:" + str)
29. }
30. }
31. </script>
32. </head>
33. <body>
34. <p>Below we demonstrate 3 types of dialog boxes</p>
35. <p>Warning and reminder dialog boxes</p>
36. <p>
37. <input type="submit" name="Submit" value="Submit" onclick="ale()" />
38.</p>
39. <p>dialog with selections</p>
40. <p>
41. <input type="submit" name="Submit2" value="Submit" onclick="firm()" />
42.</p>
43. <p>Dialog box asking for user input</p>
44. <p>
45. <input type="submit" name="Submit3" value="Submit" onclick="prom()" />
46.</p>
47. </body>
48. </html>

Page effect:

Write picture description here

2) Writing layout in Android

1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:orientation="vertical"
4. android:layout_width="fill_parent"
5. android:layout_height="fill_parent"
6.>
7. <LinearLayout
8. android:orientation="horizontal"
9. android:layout_width="fill_parent"
10. android:layout_height="fill_parent"
11. android:animationCache="true"
12. android:layout_weight="9">
13. <EditText
14. android:id="@ + id/EditText01"
15. android:layout_width="wrap_content"
16. android:layout_weight="9"
17. android:layout_height="wrap_content"
18. android:text="Please enter the URL"/>
19. <Button android:id="@ + id/Button01"
20. android:layout_width="wrap_content"
21. android:layout_weight="1"
22. android:layout_height="wrap_content"
23. android:text="Connect" />
24. </LinearLayout>
25. <WebView
26. android:id="@ + id/WebView01"
27. android:layout_width="fill_parent"
28. android:layout_height="fill_parent"
29. android:layout_weight="1"
30. />
31. </LinearLayout>

3) Write the layout of the custom dialog box Create a new prom_dialog.xml file and customize a dialog box with input composed of TextView and EditText

1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:gravity="center_horizontal"
4. android:orientation="vertical"
5. android:layout_width="fill_parent"
6. android:layout_height="wrap_content"
7.>
8. <TextView
9. android:id="@ + id/TextView_PROM"
10. android:layout_width="fill_parent"
11. android:layout_height="wrap_content"/>
12. <EditText
13. android:id="@ + id/EditText_PROM"
14. android:layout_width="fill_parent"
15. android:layout_height="wrap_content"
16. android:selectAllOnFocus="true"
17. android:scrollHorizontally="true"/>
18. </LinearLayout>

4) Obtain the WebView control and make relevant settings

Write picture description here

5) Override the onKeyDown method and return to the previous loaded page when the user presses the return key

Write picture description here

6) Set setWebChromeClient for WebView and override the method

1. // Set up WebChromeClient
2. mWebView.setWebChromeClient(new WebChromeClient() {<!-- -->
3.
4. @Override
5. // Handle alert in javascript
6. public boolean onJsAlert(WebView view, String url, String message,
7. final JsResult result) {<!-- -->
8. //Construct a Builder to display the dialog box in the web page
9. Builder builder = new Builder(MainActivity.this);
10. builder.setTitle("Prompt dialog box");
11. builder.setMessage(message);
12. builder.setPositiveButton(android.R.string.ok,
13. new AlertDialog.OnClickListener() {<!-- -->
14.
15. @Override
16. public void onClick(DialogInterface dialog,
17. int which) {<!-- -->
18. // TODO Auto-generated method stub
19. // After clicking the OK button, continue to perform the operations on the web page
20. result.confirm();
twenty one.                             }
twenty two.                         });
23. builder.setNegativeButton(android.R.string.cancel,
24. new OnClickListener() {<!-- -->
25.
26. @Override
27. public void onClick(DialogInterface dialog,
28. int which) {<!-- -->
29. result.cancel();
30.
31. }
32. });
33. builder.setCancelable(false);
34. builder.create();
35. builder.show();
36.
37. return true;
38.
39. }
40.
41. @Override
42. //Handle confirm in javascript
43. public boolean onJsConfirm(WebView view, String url,
44. String message, final JsResult result) {<!-- -->
45. Builder builder = new Builder(MainActivity.this);
46. builder.setTitle("Dialog box with selection");
47. builder.setMessage(message);
48. builder.setPositiveButton(android.R.string.ok,
49. new AlertDialog.OnClickListener() {<!-- -->
50. public void onClick(DialogInterface dialog, int which) {<!-- -->
51. result.confirm();
52. }
53. });
54. builder.setNegativeButton(android.R.string.cancel,
55. new DialogInterface.OnClickListener() {<!-- -->
56. public void onClick(DialogInterface dialog, int which) {<!-- -->
57. result.cancel();
58. }
59. });
60. builder.setCancelable(false);
61. builder.create();
62. builder.show();
63. return true;
64. }
65.
66. @Override
67. // Handle prompts in javascript
68. // message is the prompt content of the dialog box in the web page
69. // defaultValue is the default content displayed when there is no input.
70. public boolean onJsPrompt(WebView view, String url, String message,
71. String defaultValue, final JsPromptResult result) {<!-- -->
72. // Customize a dialog box with input consisting of TextView and EditText
73. LayoutInflater layoutInflater = LayoutInflater
74. .from(MainActivity.this);
75. final View dialogView = layoutInflater.inflate(
76. R.layout.prom_dialog, null);
77.
78. //Set the prompt information in the corresponding web page of TextView
79. ((TextView) dialogView.findViewById(R.id.TextView_PROM))
80. .setText(message);
81. // Set EditText to correspond to the input box in the web page
82. ((EditText) dialogView.findViewById(R.id.EditText_PROM))
83. .setText(defaultValue);
84. //Construct a Builder to display the dialog box in the web page
85. Builder builder = new Builder(MainActivity.this);
86. //Set the pop-up box title
87. builder.setTitle("Dialog box with input");
88. //Set the layout of the pop-up box
89. builder.setView(dialogView);
90. //Set button monitoring
91. builder.setPositiveButton(android.R.string.ok,
92. new AlertDialog.OnClickListener() {<!-- -->
93.
94. @Override
95. public void onClick(DialogInterface dialog,
96. int which) {<!-- -->
97.
98. // After clicking OK, obtain the input value and pass it to the web page for processing
99. String value = ((EditText) dialogView
100. .findViewById(R.id.EditText_PROM))
101. .getText().toString();
102. result.confirm(value);
103. }
104.
105. });
106.
107. builder.setNegativeButton(android.R.string.cancel,
108. new OnClickListener() {<!-- -->
109.
110. @Override
111. public void onClick(DialogInterface dialog,
112. int which) {<!-- -->
113. // TODO Auto-generated method stub
114. result.cancel();
115. }
116. });
117.
118. builder.setOnCancelListener(new DialogInterface.OnCancelListener() {<!-- -->
119. public void onCancel(DialogInterface dialog) {<!-- -->
120. result.cancel();
121. }
122. });
123. builder.show();
124. return true;
125. }
126.
127. @Override
128. //Set the progress bar of web page loading
129. public void onProgressChanged(WebView view, int newProgress) {<!-- -->
130. MainActivity.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress *100);
131. super.onProgressChanged(view, newProgress);
132. }
133.
134. @Override
135. public void onReceivedTitle(WebView view, String title) {<!-- -->
136. MainActivity.this.setTitle(title);
137. super.onReceivedTitle(view, title);
138. }
139.
140. });
141. mButton.setOnClickListener(new View.OnClickListener() {<!-- -->
142.
143. @Override
144. public void onClick(View v) {<!-- -->
145. //Get the content we entered in the edit box
146. String url = mEditText.getText().toString().trim();
147. //Determine whether the entered content is a URL
148. if(URLUtil.isNetworkUrl(url)){<!-- -->
149. //Load URL
150. mWebView.loadUrl(url);
151. }else{<!-- -->
152. mEditText.setText("Wrong input URL, please re-enter");
153. }
154. }
155. });
156.
157. }

Write picture description here

Figure 1 dialog.html page

Write picture description here

Figure 2 JavaScript warning dialog box

Write picture description here

Figure 3 JavaScript confirm dialog box

Write picture description here

Figure 4 JavaScript prompt dialog box

Summary: In this project, use the setWebChromeClient method to set a WebChromeClient object for WebView to assist WebView in processing Javascript dialog boxes, etc. Figure 4 is our customized dialog box. In Figures 2 and 3, we only need to listen for buttons. click event, and then pass our operation to Javascript for processing through the confirm and cancel methods. When you click the first button in the interface in Figure 1, the dialog box in Figure 2 will open. When you click the second button, the dialog box in Figure 3 will open. At the same time, click OK here to jump to another page, when the third button is clicked, the dialog box in Figure 4 will open, and content can be entered.

For more Android advanced guides, you can Scan the code to unlock “Android Ten Major Section Documents”

1. Android vehicle application development system study guide (with actual project practice)

2. Android Framework study guide to help you become a system-level development expert

3.2023 Latest Android Intermediate and Advanced Interview Questions Summary + Analysis, Say Goodbye to Zero Offers

4. Enterprise-level Android audio and video development learning route + project practice (with source code)

5. Android Jetpack builds high-quality UI interfaces from entry to proficiency

6. Flutter technology analysis and practical implementation, the first choice for cross-platform

7. Kotlin improves the architectural foundation in all aspects from entry to actual use

8. Advanced Android plug-in and componentization (including practical tutorials and source code)

9. Android performance optimization practice + 360° all-round performance tuning

10. From beginner to proficient in Android, the path to advancement for experts

It’s not easy to code, so pay attention. ?( ′?` )

syntaxbug.com © 2021 All Rights Reserved.