美文网首页
Hybird App中 Android 和 IOS 与网页之间的

Hybird App中 Android 和 IOS 与网页之间的

作者: 雪燃归来 | 来源:发表于2020-05-30 15:03 被阅读0次

一、 Android、IOS的双向通信对比-相同点

1、都是通过WebView来完成页面加载的
2、都是通过向Window注入对象的方式来提供可被Web端调用的方法
3、都是直接调用Web端挂载到window对象下的方法

一、 Android、IOS的双向通信对比-不同点

1、注入对象不同:Android 可提供注入对象名。IOS固定为webkit
2、JS调用Native方式不同:面向Android可以直接获取注入对象,调用方法面向IOS为相对固定的写法(window.webkit.messageHandlers.方法名.postMessage(入参对象))
3、传递数据格式不同:面向Android只能接受基本数据类型数据。面向IOS可以接受任意类型数据。
4、返回值不同:面向Android可以直接接受返回值。面向IOS没有办法直接获取返回值。

三、Android与Web端的双向通信

image.png

1、向原生端传递参数
      在原生端通过自定义的AndroidJSBridge向网页端的window对象中注入方法,然后通过window.AndroidJSBridge.androidTestFunction1('xxxx')的方式调用,实现通信。调用的时候,可以为原生端的方法传递必要的参数。
android端

/**
     *
     * window.AndroidJSBridge.androidTestFunction1('xxxx')
     * 调用该方法,APP 会弹出一个 Alert 对话框,
     * 对话框中的内容为 JavaScript 传入的字符串
     * @param str  android 只能接收基本数据类型参数
     *             ,不能接收引用类型的数据(Object、Array)。
     *             JSON.stringify(Object) -> String
     */
    @JavascriptInterface
    public void androidTestFunction1 (String str) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(str);
        builder.setNegativeButton("确定", null);
        builder.create().show();
    }

web端

<input
      type="button"
      value="调用toAndroidFunction1"
      onClick="toAndroidFunction1()"
    />

<script>
// 调用 Android Function1
    function toAndroidFunction1() {
      window.AndroidJSBridge.androidTestFunction1(
        "调用 Android 下的function1 方法"
      );
    }
</script>

2、原生返回值给网页端
      除了给原生端的方法传递参数,原生端还可以直接为我们web端返回值。
android 端

 /**
     * 调用该方法,方法会返回一个返回值给 javaScript 端
     * @return 返回值的内容为:"androidTestFunction2方法的返回值"
     */
    @JavascriptInterface
    public String androidTestFunction2 () {
        return "androidTestFunction2方法的返回值";
    }

web端

<input
      type="button"
      value="调用toAndroidFunction2"
      onClick="toAndroidFunction2()"
    />
<script>
// 调用 Android Function2
    function toAndroidFunction2() {
      var result = window.AndroidJSBridge.androidTestFunction2();
      alert(result);
    }
</script>

3、Android端直接调用web端的方法
      android端可以直接调用web端挂载到window对象下的方法。
android 端

 /**
     * 原生端调用 web 方法,方法必须是挂载到 web 端 window 对象下面的方法。
     * 调用 JS 中的方法:onFunction
     */
    public void onJSFunction1 (View v) {
        mWebView.evaluateJavascript("javascript:onFunction('android调用JS方法')", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage(s);
                builder.setNegativeButton("确定", null);
                builder.create().show();
            }
        });
    }

web 端

// 原生端调用网页端的方法
    window.onFunction = function (str) {
      alert(str);
      return "这是 onFunction 方法的返回值";
    };

三、IOS与Web端的双向通信


1、js调用OC定义的方法
      js直接调用OC定义的方法时,调用的方式跟Android相似,执行IOS中会将方法挂载在网页指定的window.webkit的对象下面,而不是跟andorid一样需要自定义JSBridge。与 Android 不同,IOS可以直接接收一个对象Object数据。
OC端
//OC在JS调用方法做的处理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //前端主动JS发送消息,前端指令动作
    if ([@"IOSTestFunction1" isEqualToString:message.name]) {
        [self IOSTestFunction1:message.body];
    } else if ([@"IOSTestFunction2" isEqualToString:message.name]) {
        [self IOSTestFunction2:message.body];
    }
}
#pragma mark - 与 Android 不同,IOS可以直接接收一个对象Object数据
- (void)IOSTestFunction1:(id)body {
    NSDictionary *dict = body;
    NSString *msg = [dict objectForKey:@"msg"];
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

web端

 <input
      type="button"
      value="调用toIosFunction1"
      onClick="toIOSFunction1()"
    />
<script>
// 调用 IOS Function1
    function toIOSFunction1() {
      var obj = {
        msg: "web 调用IOS toIOSFunction1.postMessage(obj)",
      };
      window.webkit.messageHandlers.IOSTestFunction1.postMessage(obj);
    }
</script>

2、OC不能直接返回值给web端
      oc端不能直接返回给web端,要实现类似与Android那样的功能,我们可以通过在OC端调用web预先挂载好的方法,实现相应业务。OC端可以接受挂载在window下边方法返回的直接。如下代码onFunctionIOS所示:
OC端

#pragma mark - 调用该方法,回调 web 端 onFunctionIOS 方法,并传递字符串
- (void)IOSTestFunction2:(id)body {
    
    [self.webView evaluateJavaScript:@"onFunctionIOS('IOSTestFunction2方法执行完成')" completionHandler:^(id result, NSError * _Nullable error) {
        
        NSLog(@"%@", result);
        
    }];
    
}

web端

<input
      type="button"
      value="调用toIosFunction2"
      onClick="toIOSFunction2()"
    />
<script>
// 调用 IOS Functio2
    function toIOSFunction2() {
      window.webkit.messageHandlers.IOSTestFunction2.postMessage({});
    }
    // IOS 回调 web的方法
    window.onFunctionIOS = function (str) {
      alert(str);
      return "onFunctionIOS 执行完成!";
    };
</script>

相关文章

网友评论

      本文标题:Hybird App中 Android 和 IOS 与网页之间的

      本文链接:https://www.haomeiwen.com/subject/ilnczhtx.html