h5页面与app原生页面通信——postMessage方法

背景

  • 有些页面需要经常改动,为了避免app频繁发版本,需要在app里放h5页面
  • h5页面和app有交互

解决方案

  • JS部分
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    var params = {
    'id': $id,
    'type': $type,
    'typeide': $typeide,
    'categoryId': $categoryId,
    'good_id': $good_id,
    'url': $url
    };
    function setupWvJsBridge(params){ //参数
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

    // ios postMessage
    try {
    if(isAndroid != true && isiOS == true){
    var postMsg = params;
    window.webkit.messageHandlers.AppModel.postMessage(postMsg);
    }
    } catch {}

    // android postMessage
    try {
    if(isiOS != true && isAndroid == true){
    var postMsg = params;
    window.Android.postMessage(JSON.stringify(postMsg));
    }
    } catch(error) {}
    }

参考:https://blog.csdn.net/qq_36435508/article/details/78165007