> 技术文档 > 在UniApp中使用WebView,实现双向通信_uniapp web-view

在UniApp中使用WebView,实现双向通信_uniapp web-view

目录

为什么用WebView?

一、在vue文件中创建webview

二、双向通信:

2.1、uniapp→webview

 2.2、webview→uniapp

 三、完整代码

3.1UniApp:

3.2WebView的html:


为什么用WebView?

WebView是UniApp中用于嵌入网页内容的组件,允许在应用中加载和显示网页。它适用于需要在应用中集成外部网页或HTML内容的场景,如展示帮助文档、加载第三方服务等。简单来说就是:我需要在app环境做一些uniapp的api不支持的功能,如:文件上传、音源转码等;

一、在vue文件中创建webview

 插入的时候注意下,如果小伙伴用了自己src的地址发现页面出不来,可以也换成百度的试一下,如果百度的出的来,那就是你地址有问题;

官方文档

  点击

二、双向通信:

2.1、uniapp→webview

  • vue中发送数据到html文件
 // vue中发送数据到html文件,getMsgFromApp名字自定义 myClickFn() { //  #ifdef APP-PLUS //选择到自己的webview-------h5不支持 var currentWebview = this.$parent.$scope.$getAppWebview().children()[0] currentWebview.evalJS(`getMsgFromApp(${你的数据})`) // #Endif },
  • html中接收来自 uniapp 的消息 
    // html中接收来自 uniapp 的消息    window.getMsgFromApp = function (arg) {      console.log(\'接收来自 uniapp 的消息,arg\',arg)    }

 2.2、webview→uniapp

  •  html向uniapp 发送消息
 // 向 uniapp 发送消息 function sendMessageToUniapp() { window.uni.postMessage({ data: { type: \'fromWebview\', message: \'这是来自 webview 的消息\', }, }) }
  •  uniapp接收html消息
  // 接收来自 webview 的消息 handleMessage(event) { console.log(\'收到来自 webview 的消息:\', event.detail) },

 三、完整代码

3.1UniApp:

  点击export default { data() { return {} }, methods: { // 接收来自 webview 的消息 handleMessage(event) { console.log(\'收到来自 webview 的消息:\', event.detail) }, // 发送数据到html文件 myClickFn() { //  #ifdef APP-PLUS //选择到自己的webview-------h5不支持 var currentWebview = this.$parent.$scope.$getAppWebview().children()[0] currentWebview.evalJS(`getMsgFromApp(${你的数据})`) // #Endif }, },}

3.2WebView的html:

   我的webview  //引入的js文件  
内容!!!!!!
// 接收来自 uniapp 的消息 window.getMsgFromApp = function (arg) { console.log(\'接收来自 uniapp 的消息\') } // 向 uniapp 发送消息 function sendMessageToUniapp() { window.uni.postMessage({ data: { type: \'fromWebview\', message: \'这是来自 webview 的消息\', }, }) } window.onload = function () { // 页面创建时执行 console.log(\'页面创建了\') } window.addEventListener(\'pagehide\', function (event) { if (event.persisted) { // 页面被浏览器缓存(如iOS Safari的后台标签) console.log(\'页面被缓存\'); } else { // 页面正在被销毁 console.log(\'页面被销毁\') } });