H5与原生安卓和ios交互

3 篇文章 0 订阅

单独的一个完整的交互方法

//  **支付方法**
function goToPay(query) {
        console.log(query);
        var data = {
            'type': pay_type_code,
            'query': query
        };
        
        var u = navigator.userAgent; //http请求用户代理头
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //Android终端
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        console.log('准备调起支付......');
        
        //android的处理
        if (isAndroid) {
            mainBridge = webViewJavascriptBridge;
            mainBridge.goToPay(JSON.stringify(data));
            return; //android不调用,但是需要实现方法..
        }
        console.log('吊起支付');
        
        //ios的处理
        window.webkit.messageHandlers.goToPay.postMessage(data);
    }

判断安卓还是ios做单独处理

	function aa() {
			//判断当前系统设备,对应不同的下载链接
			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终端             
			if (isAndroid) {
				// 安卓方法
			}
			if (isiOS) {
				// ios方法
			}
	}

判断微信打开

        var u = navigator.userAgent;
		var ua = navigator.userAgent.toLowerCase();
		var isWeixin = ua.indexOf('micromessenger') != -1;
		//如果是安卓手机
		if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 ){
		    if(isWeixin){
						this.flag = true;
		    }
		}

安卓还是IOS 对应APP下载地址

	//判断是 安卓还是IOS  对应APP下载地址
let u = navigator.userAgent;
if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
		 window.location.href = "http://im.hfgld.net/hanlife.apk";
}	else{
		 window.location.href = "http://itunes.apple.com/cn/app/%E6%B1%89%E5%AF%8C%E6%96%B0%E7%94%9F%E6%B4%BB/id1458588987?mt=8";
}

从原生获取参数的方法

       // 获取token
        this.getToken = function() {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    console.log("android未初始化:WebDemo");
                } else {
                    // 调用安卓方法,接收参数并return
                    return that.mainBridge.getToken();
                }
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                let iOSInfo = JSON.parse(JSON.stringify(window.iOSInfo));
                return iOSInfo.token;
            }
        };

向原生传递参数的方法

       // 点击跳转到另一个页面 ,调用时传递 { href:'跳转的url地址' }
       // bug:安卓智能接收字符串形式,所以需要把对象转化为字符串
       // bug:如果无需传递参数的交互,不传参可能会失败,可以随便传个字符串 ‘1’ 即可
        this.pageJump = function(query) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    console.log("android未初始化:WebDemo");
                } else {
                    that.mainBridge.pageJump(JSON.stringify(query));
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.pageJump.postMessage(query);
            }
        }

封装的js文件

"use strict";

/**
 * [WebDemo 主方法]
 * @comment  sangxiaokai@qq.com
 * @DateTime 2018-08-22T16:28:58+0800
 * @author sangxiaokai@qq.com
 */
function WebDemo() {
    var u = navigator.userAgent; //http请求用户代理头

    /**
     * propery
     * @type {String}
     */
    this.name = "webdemo1.0";
    this.debug = true; //开启调试
    this.isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //判断Android终端
    this.isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    /**
     * function
     * @comment  sangxiaokai@qq.com
     * @DateTime 2018-08-22T16:33:10+0800
     * @author sangxiaokai@qq.com
     * @return   {[type]}                 [description]
     */
    this.say = function () {
        if (this.debug) {
            console.log("name:", this.name);
            console.log("isandroid:", this.isAndroid);
            console.log("isIOS:", this.isIOS);
        }
        var that = this; //保存引用

        /**
         * 初始化方法
         */
        //建立bridge
        //如果是Android
        if (this.isAndroid) {
            if (this.debug) {
                console.log('setup For ..Android');
            }
            if (typeof webViewJavascriptBridge != 'undefined') {
                this.mainBridge = webViewJavascriptBridge; // android 定义的webview和js通信的bridge
            }
        }
        if (this.isIOS) {
            if (this.debug) {
                console.log('setup For ..IOS');
            }
            this.mainBridge = undefined;

            /*这段代码是固定的,必须要放到js中*/
            this.setupWebViewJavascriptBridge = function (callback) {
                if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
                if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
                window.WVJBCallbacks = [callback];
                var WVJBIframe = document.createElement('iframe');
                WVJBIframe.style.display = 'none';
                WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
                document.documentElement.appendChild(WVJBIframe);
                setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0)
            }; //
            console.log("setupWebViewJavascriptBridge is :", typeof this.setupWebViewJavascriptBridge);
            this.mainBridge = undefined; //

            /*与OC交互的所有JS方法都要放在此处注册,才能调用通过JS调用OC或者让OC调用这里的JS*/
            this.setupWebViewJavascriptBridge(function (bridge) {
                /**
                 1:扫一扫
                 2:复制
                 */
                console.log('get bridge:', typeof bridge);
                that.mainBridge = bridge;
            });
        } //isIOS


        /**
         * 实现的功能
         */
        
        // 获取状态栏高度
        this.statusHeight = function () {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    console.log("android未初始化:WebDemo");
                } else {
                    // 调用安卓定义的方法statusHeight(),接收参数并return
                    return that.mainBridge.statusHeight();
                }
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                let iOSInfo = JSON.parse(JSON.stringify(window.iOSInfo));
                return iOSInfo.statusHeight;
            }
        };
        
        // 给原生传递参数
        this.setData = function (query) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                	// 调用安卓定义的方法setData(res),传递参数
                    that.mainBridge.setData(query);
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.setData.postMessage(query);
            }
        }
        
        // 退出登录
        this.exit = function () {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                	// 调用安卓定义的方法exit(),退出APP
                    that.mainBridge.exit();
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.exit.postMessage();
            }
        }
        
        //退出APP
        this.finishApp = function (query) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                    that.mainBridge.finishApp();
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.finishApp.postMessage(query);
            }
        }


        //记录手机顶部高度
        this.statusHeight = function () {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    console.log("android未初始化:WebDemo");
                } else {
                    // 调用安卓方法,接收参数并return
                    return that.mainBridge.statusHeight();
                }
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                let iOSInfo = JSON.parse(JSON.stringify(window.iOSInfo));
                return iOSInfo.statusHeight;
            }
        };
        

        //截图,保存图片
        this.saveScreenshotToLibrary = function (query) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                    that.mainBridge.saveScreen();
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.saveScreenshotToLibrary.postMessage(query);
            }
        }
        
        //清除缓存
        this.ClearMemery = function (query) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                    that.mainBridge.clearMemery();
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.ClearMemery.postMessage(query);
            }
        }
        
        
        //更新APP
        this.updateApp = function (query) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                    that.mainBridge.updateApp();
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.updateApp.postMessage(query);
            }
        }
        
        // 扫一扫
        this.doScan = function (query) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                    that.mainBridge.doScan();
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                console.log('...................');
                console.log(query);
                window.webkit.messageHandlers.doScan.postMessage(query);
            }
        }
        
        
        // 扫一扫未使用
        // 
        this.doScan_ = function(callback) {
            if (that.debug) {
                console.log('mainBridge type is :', typeof that.mainBridge);
                console.log('callback is type :', typeof callback);
            }
            //android的处理
            if (that.isAndroid) {
                if (typeof that.mainBridge == "undefined") {
                    alert("android未初始化:WebDemo");
                } else {
                    that.mainBridge.doScan();
                }
                return; //android不调用,但是需要实现方法..
            }
            //ios的处理
            if (typeof that.mainBridge == "undefined") {
                var ret = {
                    status: -1 //未初始化
                }
                if (typeof callback != 'undefined') {
                    callback(ret);
                } else {
                    alert("未初始化:WebDemo");
                }
            }
            //初始化成功        
            var data = { type: 'scanResponseCallback:', param: [] };
            that.mainBridge.callHandler('getBlogNameFromObjC', data, function(res) {
                //是WebViewJavascriptBridge这个对象的方法提供一种数据交互通道-在你的webview和本地应用之间
                /**
                放回的格式:
                {'status':'1',
                'data':
                    {
                        'value':'12234'
                    },
                'msg':'操作失败'
                }
                */
                if (that.debug && res.status != 1) {
                    //错误
                    console.log("错误:", res.msg);
                }
                //callback
                if (typeof callback != 'undefined') {
                    callback(res);
                }
            });
        }
        

    };
    this.say();
}
export default WebDemo;

使用方法

  • main.js 引入
// webdemo.js
import WebDemo from '@/common/js/webdemo.js'
var demo = new WebDemo ();
Vue.prototype.$demo = demo
// 页面里使用
this.$demo.say()
  • html中使用
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>h5打包APP,与原生交互</title>
    </head>
    
    <body>
    </body>
    
    <!-- 引入webdemo -->
    <script src="./webdemo.js" type="text/javascript"></script>
    <script type="text/javascript">
        var webdemo = new WebDemo();
        webdemo.statusHeight() // 获取原生传递的参数:statusHeight()
        webdemo.setData('给安卓传递的参数') // 需要给原生传递参数:setData(res)
        webdemo.exit(); // 退出APP,点击事件主动触发:exit()
    </script>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小曲曲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值