uni-app跨端开发实现APP与H5之间的通讯和交互

最近在研究uni-app跨端开发APP和H5的通讯和交互,比如H5调用APP的方法,APP往H5里面传参,H5往app外面传参。话不多说,上代码!

html文件放本地的话必须放在项目根目录下的static文件夹

H5调用APP的方法

uni-app和H5的交互uni-app文件中的代码

// app 触发H5的方法
		apph5 () {
			const num = 100;
			this.wv.evalJS(`window.changeNum(${num})`); // 执行某个方法
		},
		handlePostMessage: function(evt) {
			console.log("接收到消息:" + JSON.stringify(evt.detail));
			this.$refs.uToast.show({
				position: center,
				type: success,
				message: `接收到消息: = ${JSON.stringify(evt.detail.data)}`
			});
		},
		createWebview () {
			const vm = this;

			// const wv = plus.webview.create("","custom-webview",{
			// 	plusrequire:"none", //禁止远程网页使用plus的API,有些使用mui制作的网页可能会监听plus.key,造成关闭页面混乱,可以通过这种方式禁止
			// 	uni-app: none, //不加载uni-app渲染层框架,避免样式冲突
			// 	top:uni.getSystemInfoSync().statusBarHeight+44 //放置在titleNView下方。如果还想在webview上方加个地址栏的什么的,可以继续降低TOP值
			// });
			// wv.loadURL("http://192.168.1.7:8000?a=1&b=2&c=[12,3,4]");

			const wv = plus.webview.create("/static/hybrid/index.html?a=1&b=2&c=[12,3,4]")  
			const currentWebview = this.$scope.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
			currentWebview.append(wv);//一定要append到当前的页面里!!!才能跟随当前页面一起做动画,一起关闭
			vm.wv = wv;

			// 监听plusMessage 事件
			plus.globalEvent.addEventListener(plusMessage, function(msg){
				console.log(H5页面返回的数据为:+ JSON.stringify(msg));
				if(msg.data.args.data.name == postMessage){   
					console.log(H5页面返回的数据为:+ JSON.stringify(msg.data.args.data.arg));
					vm.$refs.uToast.show({
						position: bottom,
						type: success,
						message: `接收到消息: = ${JSON.stringify(msg.data.args)}`
					});
				}
			});

			
			
			setTimeout(function() {
				wv.setStyle({
					height: 300,
					top: 400,
					position: dock,
					dock: top,
					zindex: 0
				});
				console.log(wv.getStyle())
			}, 1000);//如果是首页的onload调用时需要延时一下,二级页面无需延时,可直接获取
		},

需要参考H5 PLUS的API部分接口

经验分享 程序员 微信小程序 职场和发展