web front-end entry to the real: 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 I 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, if the IOS and Android let go each to develop a less efficient it 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需要调用的方法    // 被JS调用的方法必须加入@JavascriptInterface注解    @JavascriptInterface    public void sendMsg(String msg) {//        Log.i(TAG, "JS调用了Android的hello方法" + msg);//        Toast.makeText(mContext, "JS调用了Android的hello方法" + msg, Toast.LENGTH_SHORT).show();        //为了方便拿到上下文和ui组件,写一个回调接口。        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("你好,这是要传递的参数")
}
web前端开发学习Q-q-u-n: 784783012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法
(从零基础开始到前端项目实战教程,学习工具,职业规划)

(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: 

// 第一种调用js中代码的方法
// mWebView.loadUrl("javascript:beStronger()");
//第二种调用js中代码的方法,同时传值过去
        mWebView.evaluateJavascript("javascript:beStronger(‘" + str + "‘)", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                //此处为 js 返回的结果
                Toast.makeText(H5Activity.this, value, Toast.LENGTH_SHORT).show();
            }
        });

Code in the web follows:

function beStronger(value) {
    let box = document.getElementById("box");
    // box.innerText = value;
    box.className = "box2";
    box.innerText=value;
    return "小明你好"
}

Click native web button in the div will change when.

web front-end entry to the real: Js and Native call each other summary

(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调用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>
        web前端开发学习Q-q-u-n: 784783012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法
(从零基础开始到前端项目实战教程,学习工具,职业规划)

(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

//注册handlerwebView.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 you 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
        );
    }

Guess you like

Origin blog.51cto.com/14592820/2459418
Recommended