使用案例
1.app端(需要使用nvue)
<template> <view class="webview-box"> <button style="z-index: 999;" @click="handlePostMessage('app向url传值')">点击向url传值</button><web-view ref="webview" class="webview" src="http://191.160.11.101:8081/index?os=wx" @onPostMessage="PostMessage"></web-view> </view>
</template>
<script> export default { data() { return { url:'http://191.160.11.101:8081/index?os=wx'} }, onLoad() { this.url += '&t=' + new Date().getTime()}, methods: { // 接收h5页面发来的键值判断需要执行的操作 PostMessage(evt) { console.log("postMessage: ", evt)uni.showModal({title:"提示",content:evt.detail.data[0].msg})}, // 获取到对应webview(关键)通过evalJs执行网页的函数,可对其进行传参,完成与网页的通讯 handlePostMessage(res) { this.$refs.webview.evalJs(`handleMessage('${res}')`); } } }
</script> <style> .webview-box { position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; } .webview { flex: 1; height: 300rpx;}
</style>
2. html端
<!doctype html>
<html lang="ch" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no,viewport-fit=cover"><title>title</title><!-- uni 的 SDK,必须引用。 --> <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script><body><div id="box"></div><div class="btn" >点击</div><button id="to_shiming">向上传递数据</button></body><script> // 在引用依赖的文件后,需要在 HTML 中监听 UniAppJSBridgeReady 事件触发后,才能安全调用 uni 的 API。 document.addEventListener('UniAppJSBridgeReady', function() {// 点击某个按钮后发消息。document.getElementById('to_shiming').addEventListener('click', function() {// 这里调用uniapp的api执行消息发送uni.postMessage({data: {msg:'url向app传值'}});});});window.handleMessage = function(msg){console.log("接收到消息",msg);alert("接收到消息"+msg);document.getElementById('box').innerText = msg;}</script>
</head></html>
app端也可以通过url向html传递参数