当前位置: 代码迷 >> 综合 >> uniapp 与 webview 在app中参数传递
  详细解决方案

uniapp 与 webview 在app中参数传递

热度:107   发布时间:2023-09-19 07:43:11.0

webview默认占用全屏,建议使用uniapp原生导航栏,不然还要自己画,全局关闭的,可以单独页面开启,新增时设置top和bottom

uniapp页面

<template><view class="selectPipeline"><view class="btn"><button @click="changeBtn" type="default">确认</button></view></view>
</template><script>export default {data() {return {// 状态栏高度+原生导航高度topHeight: '',ifrSrc: '/hybrid/html/selectPipeline.html', }},onLoad() {this.gpsPosition()},methods:{// 获取经纬度gpsPosition(){uni.getLocation({type: 'gcj02',success: (res) => {console.log('当前位置:' , res);console.log('当前位置的经度:' + res.longitude);console.log('当前位置的纬度:' + res.latitude);this.ifrSrc = this.ifrSrc + '?lng=' + res.longitude + '&lat=' + res.latitude;this.getSystemInfo()}});},// 渲染webview页面init(){// #ifdef APP-PLUS// 空出导航栏高度和按钮高度var wv = plus.webview.create(this.ifrSrc,'',{top:this.topHeight,bottom:'55px'})var currentWebview = this.$scope.$getAppWebview();   currentWebview.append(wv);  //重点: 监听子页面uni.postMessage返回的值  plus.globalEvent.addEventListener('plusMessage', function(msg){  if(msg.data.args.data.name == 'postMessage'){   console.log('子页面返回的数据为:'+JSON.stringify(msg.data.args.data.arg));  }  });// #endif},// 获取系统信息getSystemInfo(){let _this = thisuni.getSystemInfo({success: function (res) {console.log('res:',res)_this.topHeight = (res.statusBarHeight+44) + 'px'_this.init()}})},changeBtn(){console.log("确认选择")}}}
</script><style lang="less" scoped>.btn{
     position: fixed;left: 0;right: 0;bottom: 0;padding: 5px 10px;button{height: 45px;background-color: #0081ff;color: #fff;}}
</style>

html,需要引入uni.webview.1.5.2.js

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> --><title>Document</title><style>body {
     background-color:greenyellow;}#btn{
     margin: 200px auto;width: 300px;height: 200px;font-size: 140px;}</style>
</head>
<body><button id="btn">按钮</button><script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script><script>var a=1;console.log(getQuery('lng'),getQuery('lat'));  //获取 uni-app 传来的值//取url中的参数值function getQuery(name) {// 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");let r = window.location.search.substr(1).match(reg);console.log(r);if(r != null) {// 对参数值进行解码return decodeURIComponent(r[2]);}return null;}document.addEventListener('UniAppJSBridgeReady', function() {//向uniapp传值document.querySelector("#btn").addEventListener("click", function () {uni.postMessage({data: {action: ++a,},});});});</script>
</body>
</html>