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

//  **支付方法**
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";
}

从原生获取参数的方法

       // 获取tokenthis.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 {// 调用安卓方法,接收参数并returnreturn 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//如果是Androidif (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(),接收参数并returnreturn 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(),退出APPthat.mainBridge.exit();}return; //android不调用,但是需要实现方法..}//ios的处理if (typeof that.mainBridge == "undefined") {console.log('...................');console.log(query);window.webkit.messageHandlers.exit.postMessage();}}//退出APPthis.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 {// 调用安卓方法,接收参数并returnreturn 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);}}//更新APPthis.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);}//callbackif (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>

H5与原生安卓和ios交互相关推荐

  1. uniapp H5与原生安卓的数据互通和方法调用

    1.准备 我这里是uniapp与原生安卓之间的相互调用,也就是原生安卓内嵌H5页面,下面先来准备一下安卓端的代码. (1).初始化的MainActivity 类定义一个 WebView private ...

  2. 高仿DY短视频APP源码,支持直播 带原生安卓和ios源码 后台PHP-带安装教程

    简介: 会员投稿互换的版本,做了一些修复修改 文件比较大 搭建有难度,具体没有细测.带安装教程的有需要的可以自己研究下载 AS 最新版 3.6.1 Xcode 最新 11.4.1 OSS 七牛 短视频 ...

  3. 【三端通用】微信即时通讯+视频聊天(安卓、IOS、小程序)项目完整版

    # 简单描述: 此产品是本人耗时12day开发出来的,采用的是uniapp框架开发出来的,可快速云打包上线,也可以进行二次开发符合自己的具体需求.         为什么要选择uni-app框架去开发 ...

  4. 混合开发与移动端--H5混合开发、H5页面的开发布局、开发注意事项、H5与原生(安卓)交互、webpack打包优化解决方案、H5调试工具、webview

    H5混合开发 混合开发.原生开发.H5开发的区别: 简述:主流APP:原生APP.H5(webapp).混合APP,相对应的定制研发即原生开发.H5开发.混合开发 原生APP开发优缺点: 可以访问手机 ...

  5. H5嵌入原生开发小结----兼容安卓与ios的填坑之路

    一开始听说开发H5,以为就是做适配现代浏览器的移动网页,心想不用管IE了,欧也.到今天,发现当初too young too simple,兼容IE和兼容安卓与IOS,后者让你更抓狂.接下来数一下踩过的 ...

  6. 移动端 h5和原生交互的方式

    一.h5传递给原生WebView的数据协议 传递的是个json字符串: {"id": "random_value","action": &q ...

  7. H5页面与ios交互返回上一级

    H5页面与ios交互时,返回上一级不兼容,安卓兼容 实现方法  (需要加return false) <a href="#" onclick="javascript: ...

  8. 客户端相关知识学习(二)之h5与原生app交互的原理

    前言 现在移动端 web 应用,很多时候都需要与原生 app 进行交互.沟通(运行在 webview中),比如微信的 jssdk,通过 window.wx 对象调用一些原生 app 的功能.所以,这次 ...

  9. h5 与原生 app 交互的原理

    作者:senntyou segmentfault.com/a/1190000016759517 现在移动端 web 应用,很多时候都需要与原生 app 进行交互.沟通(运行在 webview中),比如 ...

最新文章

  1. python爬虫入门教程--快速理解HTTP协议(一)
  2. mysql font zhushi_关于在mysql front中使用注释符报错的问题
  3. 配置spring-mvc + simple-spring-memcached
  4. 游戏大厅 从基础开始(7)--绕回来细说聊天室(中间偏下)之女仆编年史2
  5. java flatmap_Java 8 Steam API map和flatMap方法使用详解
  6. linux词语大全,简单词语大全二字学习软件-简单词语大全四字下载v1.5.3-Linux公社...
  7. Leetcode 142. Linked List Cycle II
  8. EOG眼电信号(眨眼检测)
  9. 单位转换及格式化显示
  10. java电话本怎么做_Java写的电话号码本自动化生成器,程序片段
  11. Java学习资料整合
  12. delphi 数据库_Delphi数据库编程初学者指南
  13. latex标记html样式,latex标题字体大小和样式
  14. 厦门大学904数据结构与机器学习资料与辅导
  15. oracle会计工作总结,EBS 创建会计科目 小结
  16. python+django高速公路收费管理系统的设计
  17. CC2630 7x7 更改为5X5
  18. java基础零散知识
  19. ubuntu16.04(虚拟机) 上MPD(Music Player Daemon)+MPC运行环境搭建
  20. opecv BGR转NV21

热门文章

  1. Android计算器输入错误纠正,减法都算错?安卓惊爆计算器低级错误Bug
  2. ubuntu-jupyter环境搭建
  3. android软键盘和导航栏冲突,Android隐藏导航栏/保持沉浸式模式与软键盘外观
  4. 大厂技术实现 | 图像检索及其在淘宝的应用 @计算机视觉系列
  5. 智能电视recoveryUI设计
  6. Uncaught Error: Call to undefined function lang() in framework/tpl/think_exception.tpl:82
  7. 如何运用Camtasia中的交互性?
  8. 非常详细的/etc/passwd解释
  9. Python matplotlib绘制图表
  10. 捣鼓一个记账类的小程序