1 app嵌入webview

uniapp中有两种方式可以打开H5页面,一种通过web-view标签打开页面,另一种通过plus.webview.create()方式打开
使用plus.webview.create()方式页面返回会有兼容性,所以尽量使用uniapp原生方法

2 webview与app交换联调

webview页面返回app页面需要引入uni.webview.0.1.52.js文件

  1. 普通的html页面引入使用方式
  • 在html文件中引入
//js文件引入要写在body后面
<!-- 微信 JS-SDK 如果不需要兼容小程序,则无需引用此 JS 文件。 -->  
<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>  
<!-- uni 的 SDK,必须引用。 -->  
<script type="text/javascript" src="//js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.0.1.52.js"></script>
  • webview页面中使用api
//首先监听api是否触发
document.addEventListener('UniAppJSBridgeReady', function() {  
    uni.getEnv(function(res) {  
        console.log('当前环境:' + JSON.stringify(res));  
    });  
});
//调用api返回uniapp页面
 uni.navigateTo({  
    url: '/pages/component/button/button'  
  });  
  //关闭当前webview页面
 uni.navigateBack()
  1. uniapp的H5项目中使用jsapi的方式
    开发中使用web-view标签打开的页面不需要引入api,使用plus.webview.create()方式打开的需要引入
  • 下载js库,包含 jweixin_1.4.0.js 和 uni.webview.js
    若需要兼容微信,在uni.webview.js的第一行引入 jweixin_1.4.0.js
  • 在main.js中引入本地的
const tui = require("@/static/js/uni.webview.js")
Vue.prototype.tui = tui
  • 在页面中使用对应的api
this.tui.webView.navigateTo({
	url: url
})			
				
this.tui.webView.switchTab({
	url: "/pages/index/index"
})

this.tui.webView.getEnv(res => {
  uni.showModal({
	content: JSON.stringify(res)
  });
});
  1. webview页面与app通信
  • app中监听webview传递消息的事件
<template>  
    <view>  
        <web-view src="http://192.168.1.1:3000/test.html" @message="handleMessage"></web-view>  
    </view>  
</template>  

<script>  
    export default {  
        methods: {  
            handleMessage(evt) {  
                console.log('接收到的消息:' + JSON.stringify(evt.detail.data));  
            }  
        }  
    }  
</script>
  • webview页面向app传递消息
ocument.addEventListener('UniAppJSBridgeReady', function() {  
    uni.postMessage({  
        data: {  
            action: 'postMessage'  
        }  
    });  
});

4 uniapp适配手机刘海屏问题

获取手机状态栏高度,然后获取当前webview,设置webview的top高度

<web-view :src='url' @message="handleMessage"></web-view>

js
	onReady(){
		  // #ifdef APP-PLUS
		  var currentWebview = this.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效,非v3编译模式使用this.$mp.page.$getAppWebview()
	  const sysInfo = uni.getSystemInfoSync()
		console.log(sysInfo,'statusBarHeight')
		this.topHeight=sysInfo.statusBarHeight
		console.log(this.topHeight,'topHeight')
		let that=this
		setTimeout(function() {
		  console.log(that.topHeight,'topHeight')
	      webview = currentWebview.children()[0]
	      webview.setStyle({top:that.topHeight+'px',bottom:'0px'})
	  }, 100); //如果是页面初始化调用时,需要延时一下
	  // #endif
},
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐