uniapp webview使用静态页面项APP发送消息

692 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第4天,点击查看活动详情

在uniapp中 APP端时经常会使用到webview 这时候就会需要与webview通信了,App 平台同时支持网络网页和本地网页,但本地网页及相关资源(js、css等文件)必须放在 uni-app 项目根目录->hybrid->html 文件夹下或者 static 目录下,这里我们使用的方式是利用js去创建一个webview来使用本地的网页,详细见一下代码

注意!当前写法适用于APP

//html代码
<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<style>
	body{
		
	}
	#postMessage{
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
		
	}
</style>
<body>
	<div>
		<button id="postMessage" style="background: yellowgreen;"> 发送消息</button>
	</div>
</body>
<!-- uni 的 SDK -->
<!-- 需要把 uni.webview.1.5.4.js 下载到自己的服务器 -->
<script src="./uni.webview.1.5.1.js"></script>
<script>
	// 待触发 `UniAppJSBridgeReady` 事件后,即可调用 uni 的 API。
	document.addEventListener('UniAppJSBridgeReady', function() {	
		document.getElementById('postMessage').addEventListener('click', function() {
			//给按钮添加点击事件
			document.getElementById('postMessage').addEventListener('click',()=>{
                            uni.postMessage({
                                    data: {
                                      action: 'message'
                                    }
                            });
			})
		  
		});
	})
</script>
</html>

vue的代码部分 这部分的代码是用来创建webview 并且监听html页面传递过来的信息的

<template>
	<view class="content">
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
			this.createView()
		},
		methods: {
			createView(){
				// #ifdef APP-PLUS
				const wv = plus.webview.create(
					"hybrid/html/index.html?id=11111", //这里可以填入本地网页地址 并且可以携带参数
					"gt_webview",
					{
					  background: "transparent",
					  width: "100%", //String类型,窗口的宽度.支持百分比、像素值,默认为100%.未设置width属性值时,可同时设置left和right属性值改变窗口的默认宽度.
					  height: "100%",
					})
				var currentWebview = this.$scope.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
				currentWebview.append(wv);//一定要append到当前的页面里!!!才能跟随当前页面一起做动画,一起关闭
				setTimeout(function() {
					plus.globalEvent.addEventListener('plusMessage',(msg)=>{
						console.log(msg);
					})
				
				}, 1000);//如果是首页的onload调用时需要延时一下,二级页面无需延时,可直接获取
				// #endif
			}
		}
	}
</script>

<style>
	.content {
		text-align: center;
		height: 400upx;
		margin-top: 200upx;
	}
</style>


这样我的们就完成了一个简单的app端使用本地网页向app页面发送消息的例子了