第一:首先下载官方最新的uni.webview.js,下载链接在这儿找 官方文档
第二:将下载好的webview.js放在h5的static文件夹下,
第三:在h5的index.html引入,然后写如下代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<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>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
<script type="text/javascript" src="./static/webview.js"></script>
<script type="text/javascript" >
const webViewJs = uni.webView
console.log('webViewJs',webViewJs);
</script>
</body>
</html>
在vue文件使用webviewjs返回app或者和app通信,vue代码如下
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<button type="primary" @click="back">返回app</button>
<button type="primary" @click="sendMsg">发消息给app</button>
<button type="primary" @click="toIndex">跳转到app首页</button>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
};
},
onLoad() {},
methods: {
back() {
webViewJs.navigateBack();
},
sendMsg(){
webViewJs.postMessage({
data: {
action: 'postMessage'
}
});
},
toIndex(){
webViewJs.navigateTo({
url:'/pages/index/index'
})
// 如果是tabar,使用switchTab跳转
// webViewJs.switchTab({
// url:'/pages/index/index'
// })
}
}
};
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
button {
margin: 20rpx;
}
</style>
app的webview页面接收h5传过来的值,代码如下
<template>
<view class="content">
<web-view src="http://localhost:5173/" @message="onMessage"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
onMessage(e){
console.log('e',e.detail.data);
}
}
};
</script>
<style lang="scss" scoped>
</style>
2 个评论
要回复文章请先登录或注册
赵永强 (作者)
赵永强 (作者)