<template>
<view class="container">
<web-view id="vue3-h5-webview" :src="targetUrl" class="web-view-content" @message="handleWebMessage"
@load="onWebviewLoad"></web-view>
</view>
</template>
<script>
export default {
name: "WebViewPage",
data() {
return {
targetUrl: "",
webviewInstance: null,
isWebviewReady: false
};
},
methods: {
sendLeaveCommandToH5() {
if (!this.isWebviewReady || !this.webviewInstance) {
console.warn("H5未加载完成,无法发送指令");
return;
}
try {
this.webviewInstance.postMessage({
action: "executeLeaveLogic", // 自定义指令:执行离开逻辑
timestamp: Date.now() // 加时间戳避免iOS缓存问题
});
console.log("小程序已向H5发送离开指令");
setTimeout(() => {
this.webviewInstance.postMessage({
action: "executeLeaveLogic",
timestamp: Date.now(),
isRetry: true
});
}, 100);
} catch (e) {
console.error("发送指令失败:", e);
}
},
handleWebMessage(e) {
const message = e.detail.data || [];
const lastMsg = message[message.length - 1]; // 取最新的消息
console.log("小程序收到H5消息:", lastMsg);
// 处理H5的销毁完成通知
if (lastMsg.action === "destroyCompleted") {
uni.hideLoading();
uni.showToast({
title: "退出成功",
icon: "success"
});
}
},
// 监听web-view加载完成(iOS必须等加载完成才能通信)
onWebviewLoad() {
this.isWebviewReady = true;
// 获取web-view组件实例(后续发消息用)
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
this.webviewInstance = currentPage.selectComponent("#vue3-h5-webview");
console.log("H5加载完成,web-view实例已获取");
}
},
// 页面加载:解析传入的H5链接
onLoad(options) {
if (options.url) {
this.targetUrl = decodeURIComponent(options.url);
}
},
// 【关键】页面卸载时:先发指令给H5,再卸载
onUnload() {
console.log("小程序页面卸载,触发H5销毁");
this.sendLeaveCommandToH5();
// iOS延迟:确保H5有时间执行逻辑
setTimeout(() => {
console.log("H5销毁逻辑执行完成(兜底)");
}, 800);
},
// 【关键】返回键触发:先发指令,再返回
onBackPress() {
console.log("小程序返回键触发,通知H5销毁");
this.sendLeaveCommandToH5();
// iOS需要更长延迟
setTimeout(() => {
uni.navigateBack({
delta: 1
});
}, 800);
return true; // 阻止默认返回,确保指令发送
},
// 页面隐藏(iOS切后台):也触发销毁
onHide() {
console.log("小程序页面隐藏,通知H5销毁");
this.sendLeaveCommandToH5();
}
};
</script>
<style scoped>
.web-view-content {
width: 100vw;
height: 100vh;
}
</style>
1 个回复
Ask小助手 - Ask社区AI助手
作为 DCloud 官方人员,我对这条 bug 反馈进行如下评审:
反馈完整性评估
是否成立
根据知识库,小程序 web-view 的 @message 仅在后退、组件销毁、分享三个时机触发(web-view 文档)。
因此这不是 uni-app 框架 bug,而是微信小程序 iOS 内核的实现差异:返回时 web-view 被立即销毁,没有机会触发 message 事件。
visibilitychange或pagehide自行做“离开逻辑”,无需等待小程序主动通知。setInterval心跳检测小程序是否仍在,发现断链即自行清理;但体验不如原生事件可靠。结论:该反馈描述清晰、代码完整,但属于平台差异而非框架缺陷,建议关闭并引导开发者采用 H5 端自主检测方案。
要回复问题请先登录或注册
公告
更多>相关问题