uniapp中 app与webview间的通信

9/15/2021 javascriptuniapp

# 参考资料

uniapp web-view组件 (opens new window) uniapp getappwebview (opens new window)

# webview -> app

推荐场景:可用于在webview中调用app独有的功能, 例如: 在webview中拉起微信app支付、微信app登陆...

# h5端

<!-- 引入uniapp webview sdk -->
<script src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script type="text/javascript">
  // 待触发 `UniAppJSBridgeReady` 事件后,即可调用 uni 的 API。
  document.addEventListener('UniAppJSBridgeReady', () => {
  uni.postMessage({
     data: {
       action: 'do something...'
     }
  })
  uni.getEnv(function(res) {
    console.log('当前环境:' + JSON.stringify(res));
  })
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# app端

<template>
    <view>
        <web-view src="https://xxx/your/h5.html" @message="handleMessage"></web-view>
    </view>
</template>

<script>
export default {
  methods: {
    handleMessage(evt) {
	  // 从h5发来的数据
      console.log(evt.detail.data) // [{action: 'do something...'}]
	}
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# app -> webview

推荐场景:可用于在webview中调用app功能之后的回调...

# h5端

<!-- 引入uniapp webview sdk -->
<script src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script type="text/javascript">
// 需要被app调用的方法需要挂载到window上
// 随便自定义一个方法,等待app调用
window.cusAlert = (msg) => {
  alert(msg)
}
</script>
1
2
3
4
5
6
7
8
9

# app端

<template>
    <view>
        <web-view src="https://xxx/your/h5.html"></web-view>
    </view>
</template>

<script>
export default {
  mounted () {
    const currentWebview = this.$scope.$getAppWebview()
    const ws = currentWebview.children()[0]
	ws.evalJS(`alert("在webview里弹个框")`)
	ws.evalJS(`window.cusAlert("调用自定义的弹窗")`)
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Last Updated: 9/22/2023, 6:04:11 AM