uni-app实现web-view和App之间的互相通信

1.web-view向App传递消息

官网对于uni-app使用web-view的介绍如下:web-view
在这里插入图片描述
注意事项提到postMessage方法,这就是web-view向App传递消息的方法,使用如下:
在这里插入图片描述
注意H5本身不支持uni-app里面的方法,所以在项目中引入支持调用uni-app方法的库
在这里插入图片描述
web-view页面使用:

uni.postMessage({
    data: {
        action: 'click'
    }
});

uni-app接受消息:

<view>
    <!--  #ifdef APP-PLUS -->
    <uni-status-bar></uni-status-bar>
    <!--  #endif -->
    <web-view @message="getMessage" :src="webViewUrl"></web-view>
</view>

getMessage(e) {
   console.log('webView传递过来的消息')
   const action = e.detail.data[0].action
 }

2.uni-app向web-view发送消息

(1)通过url带参数传递

uni-app页面:

<web-view @message="getMessage" :src="webViewUrl"></web-view>

computed: {
    webViewUrl() {
      return `${config.indexUrl}?accessToken=${this.accessToken}`
    }
}

web-view网页对url查询字符串进行解析即可得到数据:

/**
 * 解析url传递的参数
 */
getQuery(name) {
  // 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
  const value = window.location.hash.substr(3).match(reg)
  // 内网服务
  // const value = window.location.search.substr(1).match(reg)
  if (value != null) {
    // 对参数值进行解码
    return decodeURIComponent(value[2])
  }
  return null
}

const accessToken = this.getQuery('accessToken')
(2)evalJS方法

uni-app页面:

<web-view @message="message" :src="webViewUrl"></web-view>

methods: {
     message(arg) {
         console.log(JSON.stringify(arg))
         const  _funName = 'msgFromUniapp',
          _data = {
              msg: 'click'
          }
         const currentWebview = this.$scope.$getAppWebview().children()[0]
         currentWebview.evalJS(`${_funName}(${JSON.stringify(_data)})`)
     }
 }

web-view页面:

window.msgFromUniapp = function(arg) {
   console.log(JSON.stringify(arg))
}
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值