uniapp上使用webview与浏览器交互,支持三端(android、iOS、harmonyos next)
效果展示:
*这波绝对是走在最前面。uniapp上使用webview与浏览器交互,支持三端(android、iOS、harmonyos next)。还有部分人用的vue2的语法,目前是最新的vue3写法。废话不多说,直接上代码:
uniapp代码(app端)
import { ref, onMounted, getCurrentInstance } from "vue"; const webviewRef = ref(null); // #ifdef APP-HARMONY const context = getCurrentInstance(); // 允许访问对高级使用或库创建者有用的内部组件实例 const webwiewCtx = uni.createWebviewContext("webviewId", context.proxy); // #endif // 发送数据到网页 const sendDataToWeb = (data) => { // #ifndef APP-HARMONY // 获取所有页面路由 const pages = getCurrentPages(); // 找到最后一个索引 const index = pages.length - 1; // 获取到当前页面的webView实例 const currentWebview = pages[index].$getAppWebview(); // 取到真正的webview const webView = currentWebview.children()[0]; console.log(webView); webView.evalJS(`RequireMapMobile('${JSON.stringify(data)}')`); // #endif // #ifdef APP-HARMONY setTimeout(()=>{ webwiewCtx.evalJS(`RequireMapMobile('${JSON.stringify(data)}')`); }, 200) // #endif }; // 接收浏览器发送的消息 const messageHanle = (e) => { console.log("浏览器发送的消息", e.detail.data[0]); };
html代码(浏览器端)
Document .send{ width: 100%; height: 100vh; background-color: #ebebeb; text-align: center; font-size: 18px; font-weight: bold; } .send .content{ display: block; line-height: 100px; } * { margin: 0; padding: 0; }大家好,我是浏览器!window.RequireMapMobile = function(val){ console.log('来自App发送的数据', JSON.stringify(val)); // 修改class为send的背景颜色 document.querySelector('.content').style.color = 'gold'; } setTimeout(() => { uni.postMessage({ data: { message: '我是浏览器发送的数据!' } }); // 修改class为send的背景颜色 document.querySelector('.send').style.backgroundColor = 'pink'; }, 500);
有任何问题直接评论区留言。欢迎大家共同讨论uniapp、纯血鸿蒙相关话题。
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。