<!-- pages/index/index.vue -->
<template>
<view class="container">
<web-view id="web-view" :src="webViewUrl" @message="handleMessage" ref="webView"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
webViewUrl: 'https://www.aaaa.com/cs3.html',
webviewContext: null
};
},
onBackPress(options) {
if (options.from === 'backbutton') {
console.log('点击返回....');
this.sendMessage();
return true;
}
return false;
},
onReady() {
// 获取当前页面的 webview 实例
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
this.webviewContext = currentPage.$getAppWebview();
},
methods: {
handleMessage(event) {
// 处理 web-view 发送的消息
console.log('Message from web-view:', event.detail.data);
},
sendMessage() {
if (this.webviewContext) {
this.webviewContext.evalJS(`
if (window.postMessage) {
window.postMessage({
type: 'customEvent',
data: 'Hello from UniApp'
}, '*');
} else {
console.error('window.postMessage is not available');
}
`);
} else {
console.log('Webview context is not ready');
}
}
}
};
</script>
<style>
.container {
width: 100%;
height: 100vh;
}
</style>
外链/cs3.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>测试</title>
</head>
<body>
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script>
function sendMessage() {
try {
uni.postMessage({
data: {
action: 'message'
}
});
}catch(e){
alert(e)
}
}
window.addEventListener('message', function(event) {
console.log('Received message from UniApp:', event.data);
// 处理接收到的消息
if (event.data.type === 'customEvent') {
alert(event.data.data);
}
});
</script>
<button onclick="sendMessage()" style="margin-top: 50%;">按钮</button>
</body>
</html>
2 个回复
BoredApe - 有问题就会有答案。
请参考我的这篇回答:https://ask.dcloud.net.cn/question/165493
模拟jsBridge去实现
1***@qq.com
还需要的话,请联系微信:lxj1125624001,我可以为你提供