In the comparison of the efficiency of various JsBridge calls, we have summed up what way we should interact with WebView and JavaScript. In this article, we will formally enter the topic, step by step to achieve a complete WebView and JavaScript interaction.

Demo

GIF town building, demonstrate the order of function points is: 5-1-2-3-4

How do we generate the HTML pages we need?

When we get WebView and JavaScript interaction skills and are ready to try, we will be confused by this problem. I am not the front end of the f * * k, so I can’t write the HTML page I want right away.

w3schoolWhat is?

What is? Why don’t you click on it?

We need the HTML page

Following the simple tutorial of W3School, we can put together the page we need, as shown below.

Five features we’re going to implement

  • The Android Native side invokes javascript scripts in HTML
  • The Android Native side calls javascript scripts in HTML and passes parameters
  • Javascript scripts in HTML call functions on Android Native
  • Javascript scripts in HTML call functions on the Android Native side and pass parameters
  • Complete interaction process between JAVASCRIPT script in HTML and Java code in Android Native

The Android Native side invokes JAVASCRIPT scripts in HTML

In this example, the Java code of the Android Native terminal directly calls the JS script in the HTML page to change the subtitle of the HTML page. The code of Android Native is as follows:

mCallJsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MCallJsWithArgsBtn. SetText (" Native calls the WebView and JS script "); mWebView.loadUrl("javascript:changeDemoSubtitle()"); }});Copy the code

The HTML equivalent js method is:

Function changeDemoSubtitle(){document.getelementById ("subtitle").innerhtml =" I added something ";Copy the code

The Android Native side calls the JAVASCRIPT script in HTML and passes the parameters

The code of Android Native is as follows:

mCallJsWithArgsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MCallJsWithArgsBtn. SetText (" parameter is: "+ showDevInfo ()); showDevInfoToH5(); }}); Private String showDevInfo() {return "showDevInfo(' phone MODEL :" + Android.os.build. MODEL + ",SDK version :" + Android. OS. Build. VERSION. The SDK + ", the system VERSION: "+ android. OS. Build. VERSION. RELEASE +" ') "; } private void showDevInfoToH5() { mWebView.loadUrl("javascript:" + showDevInfo()); }Copy the code

The HTML equivalent js method is:

function showDevInfo(info){
document.getElementById("subtitle").innerHTML=info;
Copy the code

Javascript scripts in HTML call functions on Android Native

The HTML equivalent js method is:

function disp_confirm(){
    confirm();
}
Copy the code

The code of Android Native is as follows:

mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            Toast.makeText(MainActivity2.this, "Android_Native_Toast!", Toast.LENGTH_SHORT).show();
            }
            result.confirm();
            return true;
        }
    });
Copy the code

Javascript scripts in HTML call functions on the Android Native side and pass parameters

The HTML equivalent js method is:

function disp_confirm_with_args(message){
    confirm(message);
    }
Copy the code

The code of Android Native is as follows:

mWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { Toast.makeText(MainActivity2.this, "Android_Native_Toast! "+ message, toast.length_short).show(); } result.confirm(); return true; }});Copy the code

Complete interaction process between JAVASCRIPT script in HTML and Java code in Android Native

The HTML equivalent js method is:

function disp_confirm_with_args(message){
    confirm(message);
    }
    
Copy the code

The code of Android Native is as follows:

mWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { if ("getDevInfo".equals(message)) { showDevInfoToH5(); } } result.confirm(); return true; }}); Private String showDevInfo() {return "showDevInfo(' phone MODEL :" + Android.os.build. MODEL + ",SDK version :" + Android. OS. Build. VERSION. The SDK + ", the system VERSION: "+ android. OS. Build. VERSION. RELEASE +" ') "; } private void showDevInfoToH5() { mWebView.loadUrl("javascript:" + showDevInfo()); }Copy the code

Android Native terminal code complete display:

The Activity code:

package cn.mtalks.jsbridgedemo; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; public class MainActivity2 extends Activity { private WebView mWebView; private Button mCallJsBtn; private Button mCallJsWithArgsBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_2); initView(); initWebView(); } private void initView() { mWebView = (WebView) findViewById(R.id.webview); mCallJsBtn = (Button) findViewById(R.id.call_js_without_args_btn); mCallJsWithArgsBtn = (Button) findViewById(R.id.call_js_with_args_btn); mCallJsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MCallJsWithArgsBtn. SetText (" Native calls the WebView and JS script "); mWebView.loadUrl("javascript:changeDemoSubtitle()"); }}); mCallJsWithArgsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MCallJsWithArgsBtn. SetText (" parameter is: "+ showDevInfo ()); showDevInfoToH5(); }}); } private void initWebView() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl("file:///android_asset/JsDemo.html"); mWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { if ("getDevInfo".equals(message)) { showDevInfoToH5(); } else if (TextUtils.isEmpty(message)) { Toast.makeText(MainActivity2.this, "Android_Native_Toast!" , Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity2.this, "Android_Native_Toast! "+ message, toast.length_short).show(); } result.confirm(); return true; }}); } private String showDevInfo() {return "showDevInfo(' phone MODEL :" + Android.os.build. MODEL + ",SDK version :" + Android. OS. Build. VERSION. The SDK + ", the system VERSION: "+ android. OS. Build. VERSION. RELEASE +" ') "; } private void showDevInfoToH5() { mWebView.loadUrl("javascript:" + showDevInfo()); }}Copy the code

XML code






    

    

    Copy the code





Copy the code

Helpful hints

In fact, in JavaScript calls Java native methods, Google’s official implementation method should use JavaScript interface mode. However, this method has security vulnerabilities prior to Android4.2, which is interesting to see here. After Android4.2, @javascriptInterface annotation was added to solve the problem. Considering that the current Android version is too fragmented, it is not suitable to use JavascriptInterface, which is also the reason why it was not included in the efficiency comparison in the previous article.

The above is a complete example of WebView and JavaScript interaction. You can use the ShouldInterceptRequest method introduced in the previous article to implement this example yourself.

The next trailer

Webview page display optimization. In addition to the HTML page optimization itself, what can be done in Android Native to optimize the loading speed? The next article will give you answers, such as public Js method extraction into local, Js,CSS, image resource preloading and so on.