一、应用页面(web-view)

<template>
	<view>
		<web-view @message="handleMessage" src="https://uniapp.dcloud.io/static/web-view.html"></web-view>
	</view>
</template>
<script>
data(){
	return {
		wv: null,
	}
},
onReady() {
	  let _this = this
	  // #ifdef APP-PLUS
      //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用  plus.webview.currentWebview()无效
		var currentWebview = this.$scope.$getAppWebview() 
		setTimeout(() => {
			// 获取webview内容实例
			this.wv = currentWebview.children()[0]
			
			// 此处为测试代码,可根据需求更改为按钮点击发送消息及实时发送
			setTimeout(()=>{
				_this.upH5Event('我是应用,我给你传递消息了')
			}, 2000)
		}, 1000); //如果是页面初始化调用时,需要延时一下
	// #endif
},
methods: {
	  //向H5页面发送消息
	   upH5Event(msg){
		   //这里必须序列化!!!!!!~~~~~关键地方
		   msg = JSON.stringify(msg)
		   // 注意postJS:此处的postJS为h5中全局方法;若使用vue需要声明全局方法。
		   this.wv.evalJS(`postJS(${msg})`);
	   },
	   // 接收h5传递的消息
	   handleMessage(evt) {
		 console.log('h5向应用传递的消息是:',evt)
	   },
}
</script>

二、h5页面

1.引入uni.webview.1.5.4.js(可下载在本地)

下载地址:uni.webview.1.5.4.js

// main.js
import Vue from 'vue';
import App from './App';
// 引入uni.webview.1.5.2.js
import '@/static/uni.webview.1.5.2.js'

// 接收来自应用的消息
//定义全局方法,接收来自应用的信息
window.postJS = (msg) => {
	console.log('来自应用的消息', msg)
}

2.h5向应用传递消息

// index.vue

 <script>
 onReady() {
	document.addEventListener('UniAppJSBridgeReady', function() {
		setTimeout(()=>{
			// 重点:uni.postMessage在实际运行中总是报not a function;
			// 然后运行到浏览器测试查看,uni.webView中存在postMessage方法,更改测试后可正常调用
			// 向应用发送消息
			uni.webView.postMessage({
				data: {
					order: 'playRecord'
				}
			});
		}, 1000)
	});
},
 </script>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐