当前位置: 代码网 > it编程>前端脚本>Vue.js > uniapp webview和H5通信的3种方式代码示例

uniapp webview和H5通信的3种方式代码示例

2024年05月15日 Vue.js 我要评论
前言uniapp可以打包成多个端,再和h5通信的方式中,涉及到uniapp和h5通信,app和h5通信,小程序和h5通信。其中的h5端分为非uniapp打包的h5和uniapp打包的h5,这两者的区别

前言

uniapp可以打包成多个端,再和h5通信的方式中,涉及到uniapp和h5通信,app和h5通信,小程序和h5通信。其中的h5端分为非uniapp打包的h5和uniapp打包的h5,这两者的区别其实就是uniapp的h5里面已经有了uni这个定义,所以不能再uniapp里面直接用官方提供的那个js需要重新定义js里面的定义

app和h5的通信

uniapp打包成的app,h5向webview发送消息,按照官方的文档就可以webview,需要注意的就是如果h5是uniapp的,需要更换一下官方那个js里面的uni变量.

  • 引入这个js,需要配置一个html模板页面,新建一个文件,然后再配置里面加上这个文件

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="facebook-domain-verification"
      content="ubjskcwra0ommj0ts7gldbkenw4bei"
    />
    <link rel="stylesheet" href="<%= base_url %>static/index.css" rel="external nofollow"  />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"
    />
    <script>
      var coversupport =
        "css" in window &&
        typeof css.supports === "function" &&
        (css.supports("top: env(a)") || css.supports("top: constant(a)"));
      document.write(
        '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
          (coversupport ? ", viewport-fit=cover" : "") +
          '" />'
      );
    </script>

    <title></title>
  </head>

  <body>
    <div id="app">
      <!--app-html-->
    </div>
    <!-- <script type="module" src="/main.js"></script> -->
  </body>
  <script
    type="text/javascript"
    src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"
  ></script>
	
  <script
    type="text/javascript"
    src="<%= base_url %>static/js/uni.webview.js"
  ></script>

  <script>
    wx.miniprogram.getenv(function (res) {
      console.log("当前环境:" + json.stringify(res));
    });
    document.addeventlistener("uniappjsbridgeready", function () {
      webuni.webview.getenv(function (res) {
        console.log("当前环境:" + json.stringify(res));
      });

      // uni.webview.navigateto(...)
    });
  </script>
</html>

  • 在需要的地方发送消息就可以了
      webuni.postmessage({
          data: {
            action: "fabuyuzhan",
            params: {},
          },
        });

小程序和h5的通信

小程序和h5通信有限制,没有message那种实时的接收消息,小程序只有页面销毁的时候才会发送消息,这个感觉就没什么用处了,而且还需要引入微信的那个js,才能使用,我建议的处理方式是跳转页面吧

         webuni.navigateto({
            url: "/mysubpages/pages/preview/previewindexlist",
            success: (res) => {
              console.log(res); // 页面跳转成功的回调函数
            },
            fail: (err) => {
              console.log(err); // 页面跳转失败的回调函数
            },
          });

uniapp开发的app,没用webview而是用的iframe嵌入。

客户端使用app开发的,但是有一个h5是小游戏,使用webview的时候有个问题,就是无法很好的控制导航栏和状态栏,有时候在小游戏里面点击,进入全屏,但是退出的时候无法退出当前页面,而要先退出全屏然后再退出页面,经过测试,发现直接用iframe比较好控制,但是iframe通信没有webview通信方便,需要用的renderjs

<template>
	<view>
		<iframe id="iframe" :style="{ width: framewidth + 'px', height: frameheight + 'px' }" :src="typeurl"
			ref="iframe">
		</iframe>
		<!-- 		<web-view id="iframe" :style="{ width: framewidth + 'px', height: frameheight + 'px' }" :src="typeurl"
			ref="iframe">
		</web-view> -->
	</view>
</template>
<script>
	export default {
	method:{
				receivemessage(arg) {
				console.log("接收到renderjs回传的消息", arg);
				// const action = data.data.data.arg.action;
				// console.log('收到消息 arg', data.data.data.arg);
				const action = arg.action;
				console.log(" 收到消息action", action);
			},
	}
}
</script>
<script module="test" lang="renderjs">
	export default {
		mounted() {
			//注册消息方法
			window.addeventlistener("message", this.receivemsg, false);
		},
		methods: {
			receivemsg(data) {
				console.log('收到renderjs消息', data);
				const arg = data.data.data.arg;
				console.log('收到消息 arg', data.data.data.arg);
				if (arg) {
					//通知方法,然后去做处理
					this.$ownerinstance.callmethod('receivemessage', data.data.data.arg)
				}
			},
		}
	}
</script>

附: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))
}

总结 

到此这篇关于uniapp webview和h5通信的3种方式的文章就介绍到这了,更多相关uniapp webview和h5通信内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com