内嵌网页 应用与网页间的通信
在使用uni-app开发的app应用里内嵌非应用内的静态文件的网页,相互通信分两种情况
首先附上uni-app web-view官网链接web-view介绍
1、网页向应用传值
应用中监听 web-view 的 message 事件
<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>
从 网页 向应用发送消息
document.addEventListener('UniAppJSBridgeReady', function() {
uni.postMessage({
data: {
action: 'postMessage'
}
});
});
详情可参考链接 网页传值应用
2、应用传值网页
实质上就算 解析 window.location.search路径获取参数
应用代码
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
<view>
<web-view :webview-styles="webviewStyles" :src="url"></web-view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
webviewStyles: {
progress: {
color: '#FF3333'
}
},
url:'http://localhost:9004?data=' + '123456'
}
},
onLoad(options) {
if(options && options.url){
console.log(options.url)
}
},
methods: {
}
}
</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;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
网页代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>beego api aplication demo</title>
</head>
<body>
<div class="demo">
<input type="text" value="" onchange="inptt1(this.value)">
<input type="password" value="" onchange="inptt2(this.value)">
<button type="submit" class="btn" onclick="submint()">确定</button>
</div>
</body>
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script>
var userName = '';
var userPhone = '';
function inptt1(val){
if(val){
this.userName = val
}
}
function inptt2(val){
if(val){
this.userPhone = val;
}
}
function submint(){
console.log(this.userName,this.userPhone)
if(this.userName && this.userPhone){
var ajax = new XMLHttpRequest();
ajax.open('get','http://192.168.1.33:8080');
ajax.send();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
console.log(ajax.response)
}
}
}
}
console.log(getQuery('data')); //获取 uni-app 传来的值
function getQuery(name) {
// 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if(r != null) {
// 对参数值进行解码
return unescape(r[2]);
}
return null;
}
</script>
<style>
.btn{
width: 80px;
height: 30px;
}
</style>
</html>
这里搭建了node本地服务器 使用一个index.html作为网页

本文介绍了在uni-app应用中使用web-view内嵌网页,并详细阐述了网页如何向应用传值以及应用如何传值给网页的方法,包括监听message事件和通过window.location.search解析参数。还提供了uni-app官方web-view组件的链接以及示例代码。
1万+





