[Android Security] Interaction between Java and JS in Android

Interaction between Java and JS in Android

Reference: https://segmentfault.com/a/1190000011487440

Use of WebView

Initialize WebView

 WebView  webView= (WebView) findViewById(R.id.webview);
 webView.loadUrl("file:///android_asset/index.html");

Before interacting, you need to enable WebView's support for JS

WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);

Java calls JS method

  • Through WebView's loadUrl()
  • via WebView's evaluateJavascript()

First define an html file, and then place it in the asset directory

<html>

<head>
    <title>我的页面</title>
    <meta charset=utf-8> 
    <script type="application/javascript">
        function alertTest() {
      
      
            alert("alerttest");
        }
    </script>
</head>

<body>
    <p>Android Java JS 交互测试</p>
</body>

</html>

(1) Call the JS method through loadUrl

mWebView.post(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                mWebView.loadUrl("javascript:alertTest()");
            }
        });

(2) Call the JS method through evaluateJavascript

mWebView.evaluateJavascript("javascript:alertTest()", new ValueCallback<String>() {
    
    
            @Override
            public void onReceiveValue(String value) {
    
    
                Toast.makeText(WebViewActivity.this, value, Toast.LENGTH_SHORT).show();
            }
        });

When these two methods are called at the beginning, the problem is that an error message is reported. The error message indicates that the called JS method has not been defined. The reason for the problem is that the JavaScript file is not fully completed when called in the oncreate or onResume method. The loading is complete, so this problem occurs, which can be solved by listening to the WebView's loading event and delaying the call.

JS calls Java method

  • JavascriptInterface via WebView
  • Intercept loading information through WebViewClient.shouldOverrideUrlLoading()
  • Intercept console information through WebChromeClient.onConsoleMessage()
  • Through WebChromeClient.onJsPrompt(), onJsAlert(), onJsConfirm() to intercept the events of the corresponding web pop-up box

(1) JavascriptInterface via WebView

① Define the interactive classes and methods related to JS, and mark the methods with @JavascriptInterface annotation

public class JSTest {
    
    

  private Context mContext;

  public JSTest(Context context) {
    
    
      mContext = context;
   }

  @JavascriptInterface
  public void showToast(String str) {
    
    
       Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
  }
}

@JavascriptInterface is used to mark methods that can be called by WebView

② Add the JavaScriptInterface (that is, the class name JsTest) to WebView, and specify a name "JsTest" for it, which will be used in the JS file

 mWebView.addJavascriptInterface(new JsTest(context), "JsTest");

addJavascriptInterface(Object object, String name) is used to inject a Java object as a global variable into the JavaScript environment
, so that JavaScript code can use all public methods of the Java object

As I understand it, addJavascriptInterface is used to associate a Java class (interface) with a JavaScript class.

③ JS calls the Java method

 function showToast() {
    
    
        JsTest.showToast("来自Web调用");
 }

(2) Through the callback function onConsoleMessage() of WebView

In WebChromeClient, there is a function callback onConsoleMessage()
. When js has a console message, onConsoleMessage will be called back.
Therefore, the onConsoleMessage method can be customized by Override, so that js can call the onConsoleMessage method on the java side by triggering the console message, and then call other codes.

① Define the callback method in WebChromeClient

 @Override
    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
    
    
        String msg = consoleMessage.message();
        if ("showToast".equals(msg)) {
    
    
            Toast.makeText(mContext, "来自Web Toast测试", Toast.LENGTH_SHORT).show();
        }
        return super.onConsoleMessage(consoleMessage);
    }

② JS outputs messages to the console

 function consoleTest() {
    
    
     console.log("showToast");
 }

Guess you like

Origin blog.csdn.net/qq_39441603/article/details/131199631