Js and Native call each other summary

I. Introduction

   There are now a number of web app is loaded by a native ios, Android achieved, as shown, so we call Hybrid App app

                              

    So why use a hybrid app do? Personally think that there are two reasons: 1. to improve development efficiency, for example in relation to nail some OA operations such as punch, leave time and other functions, is clearly an embedded web page will be able to meet demand, so that if the IOS and Android go to each develop a so efficiency is very low. 2. improve iterative efficiency. To the Mall, for example, store page will change according to market conditions in real time, such as during a variety of holiday activities to do promotions. So this time if virgin, then iteration and other users to upgrade this activity may have passed, but the nest a web page with nested webview only need to make a web page in the modified hybrid app will immediately modified so that efficiency is very high.     

     hybrid app is actually using the native components webview to load a url and let js native call each other to achieve a variety of functions, then the next I put the case js and Native call each other to make a summary.

Second, the native api realization: js and native call each other

  To get native js and call each other for a webview basic setting is to allow js script execution

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

(A), js call native

   Suppose I now have a demand: the click of a button in the web, will deliver value to the web in native and displayed in TextView component. So how to achieve this demand?

  The first step: js method to be called is defined in the java code

  JS method need to call // Define 
// JS method is called must join @JavascriptInterface comment
@JavascriptInterface
public void SendMsg (String msg) {
// Log.i (TAG, "JS hello method called Android the" + msg) ;
// Toast.makeText (mContext, "JS hello method called Android the" + msg, Toast.LENGTH_SHORT) .Show ();
// get context for the convenience and ui component, write a callback interface.
mJSBridge.sendMsg (MSG);
}

  It should be noted that, 1. To add "@JavascriptInterface" annotation methods above, 2. method definition must be public

  Step two: add to webview js scripting interface.

 mWebView.addJavascriptInterface(jsInterface, "Android_Interface");

  void addJavascriptInterface (Object object, String name), this method has two parameters, the first one is a webview injection js java object context, the second parameter is the name of the object in the script to js exposed, i.e., What is written here, what would be the time to write js call native.

  The third step: the native method call using js

function sendMsg() {
    Android_Interface.sendMsg ( " parameter Hello, this is to be passed ." )
}

  

 

(Two), Native call js

  Native call js method, for example, where we achieved a native of button clicks to change the web in the div style. So this how to achieve it?

  Here webview direct use of api can be achieved. Android code as follows:  

        // The first call js code method
 //         mWebView.loadUrl ( "JavaScript: beStronger ()");
         // The second method is called js code, while by value in the past 
        mWebView.evaluateJavascript ( " JavaScript: beStronger ( ' " + STR + " ') " , new new ValueCallback <String> () {
            @Override
            public  void onReceiveValue (String value) {
                 // Here js result is returned 
                Toast.makeText (H5Activity. the this , value, Toast.LENGTH_SHORT) the .Show ();
            }
        });

  Code in the web follows:

function beStronger(value) {
    let box = document.getElementById("box");
    // box.innerText = value;
    box.className = "box2";
    box.innerText = value;
     return  " Bob hello " 
}

  Click native web button in the div will change when.

 

(III), there may be security issues

  But when native js call, there may be security issues. Specific causes and solutions can refer to this article. "You do not know the Android WebView use loopholes" . If you do app that security is extremely demanding, how to do it? It is recommended that a third-party library Android: JSBridge

Third, the third-party libraries to achieve: js and native call each other

  About the introduction of third-party libraries, in documentation already said very clearly: The library is a bridge java and js call each other, it is between java and js call provides a safe and convenient way to each other.

(A), third-party libraries

  The first step is to introduce the library in the app / build.gradle file.

 repositories {
        // ...
        maven { url "https://jitpack.io" }
    }
dependencies {
    .....  
    compile 'com.github.lzyzsd:jsbridge:1.0.4'
}

  Then add custom components, BridgeWebView in the layout, the assembly inherited from the native WebView assembly.

 <-! Webview web presentation call Java ->
    <com.github.lzyzsd.jsbridge.BridgeWebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.github.lzyzsd.jsbridge.BridgeWebView>

(Two), js call native

  The core of this framework is used: the registration of the call handler.

  Js achieve first call native, first to "registered handler" in java native code is as follows

//注册handler
webView.registerHandler("submitFromWeb", new BridgeHandler() { @Override public void handler(String data, CallBackFunction function) { Log.i(TAG, "handler = submitFromWeb, data from web = " + data); function.onCallBack("submitFromWeb exe, response data from Java"); } });

  After registering the handler, you can call js handler specified in the code, and the above example, we registered handler is "submitFromWeb", js handler java can be registered by calling the following manner.

 WebViewJavascriptBridge.callHandler(
        'submitFromWeb'
        , {'param': str1}
        , function(responseData) {
            document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData
        }
    );

(Three), Native call js

   Native call first to achieve js, then first have registered handler in the js

  WebViewJavascriptBridge.registerHandler("functionInJs", function(data, responseCallback) {
        document.getElementById("show").innerHTML = ("data from Java: = " + data);
        var responseData = "Javascript Says Right back aka!";
        responseCallback(responseData);
    });

  Js registered handler in the future, java code will be able to specify the name of the call handler 

 webView.callHandler("functionInJs", new Gson().toJson(user), new CallBackFunction() {
        @Override
        public void onCallBack(String data) {

        }
    });

(Four), need to pay attention

  The library will register a WebViewJavascriptBridge object to the window object. So in your js code before using WebViewJavascriptBridge object, you must check whether WebViewJavascriptBridge object exists. If WebViewJavascriptBridge object does not exist, you can listen WebViewJavascriptBridgeReady event as follows:

  

  if (window.WebViewJavascriptBridge) {
        //do your work here
    } else {
        document.addEventListener(
            'WebViewJavascriptBridgeReady'
            , function() {
                //do your work here
            },
            false
        );
    }

 

四、One More Thing

  Behind all the blog demo will be on BlogDemoWorkSpace on github, depending on the technology stack: Android, Web, java categories placement. If you feel there is a need to download a one-time down, choose a place to learn to read on the line Le. js and native code for each call

 

 

 

Guess you like

Origin www.cnblogs.com/dashwood/p/11539614.html