Parse the interaction between webview and js in Android

  • 2020-05-17 06:20:07
  • OfStack

1.android USES webview to invoke the js code on the web page.
Android can realize the interaction with js through webview, and call js code in the program. You only need to set the js property of webview control to true, and then directly call loadUrl, as shown below:
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("javascript:test()");

2. Call the java code method in android on the web page
To invoke the java code in a web page, you need to add javascriptInterface to the webview control. As follows:


mWebView.addJavascriptInterface(new Object() { 
            public void clickOnAndroid() { 
                mHandler.post(new Runnable() { 
                    public void run() { 
                        Toast.makeText(Test.this, " Test call java", Toast.LENGTH_LONG).show();
                    } 
                }); 
            } 
        }, "demo");

In a web page, just call it like you would call js method 1
< div id='b' > < a onclick="window.demo.clickOnAndroid()" > b.c < /a > < /div >

3. The Java code calls js and passes arguments
You first need an js function with arguments, such as function test(str), and then simply pass in the arguments when you call js, as shown below:
mWebView.loadUrl("javascript:test('aa')");

4. Call java function in Js and pass parameters
First, a function form with parameters is needed, but it should be noted that the parameters here need the type final, that is, they cannot be modified later. If you need to modify the value, you can first set the intermediate variable and then modify it. As follows:


mWebView.addJavascriptInterface(new Object() { 
            public void clickOnAndroid(final int i) { 
                mHandler.post(new Runnable() { 
                    public void run() { 
                                int j = i;
                                j++;
Toast.makeText(Test.this, " Test call java" + String.valueOf(j), Toast.LENGTH_LONG).show();
                    }
                });
            } 
        }, "demo");

Then on the html page, make use of the following code < div id='b' > < a onclick="window.demo.clickOnAndroid(2)" > b.c < /a > < /div > .
Can implement the call


Related articles: