1***@qq.com
1***@qq.com
  • 发布:2024-11-08 15:13
  • 更新:2024-11-12 20:49
  • 阅读:144

webview跟外链HTML通讯目前只能做到子传消息给父,做不到父传子,付费谁能解决

分类:uni-app

<!-- 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>

2024-11-08 15:13 负责人:无 分享
已邀请:
BoredApe

BoredApe - 有问题就会有答案。

1***@qq.com

1***@qq.com

还需要的话,请联系微信:lxj1125624001,我可以为你提供

要回复问题请先登录注册