uni-app开发的h5用在uni-app鸿蒙 webview中无法通信安卓iOS均正常

uni-app开发的h5用在uni-app鸿蒙 webview中无法通信安卓iOS均正常

信息类别 详情
产品分类 uniapp/H5
PC开发环境 Windows
操作系统版本 Win11
HBuilderX类型 正式
HBuilderX版本 4.85
浏览器平台 Chrome
浏览器版本 鸿蒙next
项目创建方式 HBuilderX

操作步骤:

<template>  
    <view class="content">  
        <view class="text-area">  
            <text class="title">{{title}}</text>  
        </view>  
        <view class="" @click="post">  
            发送消息  
        </view>  
    </view>  
</template>  

<script>  
    import y_uni from "y_uniwebview"  
    export default {  
        data() {  
            return {  
                title: 'h5Uniapp'  
            }  
        },  
        onLoad() {  

        },  
        methods: {  
            post() {  
                console.log("din", y_uni);  
                y_uni.postMessage({  
                    data: {  
                        action: 'message',  
                        data: 'hellosam'  
                    }  
                });  
            }  
        }  
    }  
</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>

预期结果:

<web-view id="webview" :src="biaoxunUrl" @load="loadedWebView" @message="message"  
        @onPostMessage="message"></web-view>  
message(e) {  
        console.log(e.detail.data);  
        let action = e.detail.data[0].action  
        console.log(action);}

实际结果:

message(e) {  
        console.log(e.detail.data);  
        let action = e.detail.data[0].action  
        console.log(action);方法不调用  
}

bug描述:

uniapp开发的h5 用在uniapp webview中通信不生效


更多关于uni-app开发的h5用在uni-app鸿蒙 webview中无法通信安卓iOS均正常的实战教程也可以访问 https://www.itying.com/category-93-b0.html

9 回复

npm install yqc_uni_webview@1.0.0 这个库兼容了鸿蒙

更多关于uni-app开发的h5用在uni-app鸿蒙 webview中无法通信安卓iOS均正常的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


你兼容了是吧,感谢反馈。

回复 DCloud_UNI_OttoJi: 是的 解决了 通过我写的这个库 或者把库写到本地引入使用即可 导出使用 // module.exports = y_uni; export default y_uni;

h5的项目是用uniapp打包出来的 我看 https://www.npmjs.com/package/y_uniwebview?activeTab=readme  这个是对uniapp打包的h5做了兼容 鸿蒙却没生效 是不是哪里还需要兼容一下

这个三方依赖上次更新是两年前,内置的 jssdk 可能没有考虑鸿蒙的兼容 要是先 uniapp 打出来的网页,作为 webview 容器内容,希望做通讯,其他不复杂。
网页端引入 jssdk,添加检测代码即可,我建议你看一下这个网页的源码,尝试改一下,看是否功能正常,如果正常了就联系作者做个升级。
view-source:https://hellouniapp.dcloud.net.cn/html/web-view.html 这个源码

view-source:https://hellouniapp.dcloud.net.cn/html/web-view.html 这个在鸿蒙是可以的通信的 这个是h5直接写的页面和uniapp生成的H5有区别 现在就看能不能把https://www.npmjs.com/package/y_uniwebview?activeTab=readme这个源码改下用最新的https://gitcode.com/dcloud/uni-app/blob/dev/dist/uni.webview.1.5.6.js

let y_uni;
! function(e, n) {
y_uni=n();
return
console.log(666888)
console.log(n())
“object” == typeof exports && “undefined” != typeof module ? module.exports = n() : “function” == typeof define &&
define.amd ? define(n) : (e = e || self).y_uni = n()
}(this, (function() {
“use strict”;
try {
var e = {};
Object.defineProperty(e, “passive”, {
get: function() {
!0
}
}), window.addEventListener(“test-passive”, null, e)
} catch (e) {}
var n = Object.prototype.hasOwnProperty;

function i(e, i) {  
    return n.call(e, i)  
}  
var t = [];  

function o() {  
    return window.__dcloud_weex_postMessage || window.__dcloud_weex_  
}  

function a() {  
    return window.__uniapp_x_postMessage || window.__uniapp_x_  
}  
var r = function(e, n) {  
        var i = {  
            options: {  
                timestamp: +new Date  
            },  
            name: e,  
            arg: n  
        };  
        if (a()) {  
            if ("postMessage" === e) {  
                var r = {  
                    data: n  
                };  
                return window.__uniapp_x_postMessage ? window.__uniapp_x_postMessage(r) : window.__uniapp_x_  
                    .postMessage(JSON.stringify(r))  
            }  
            var d = {  
                type: "WEB_INVOKE_APPSERVICE",  
                args: {  
                    data: i,  
                    webviewIds: t  
                }  
            };  
            window.__uniapp_x_postMessage ? window.__uniapp_x_postMessageToService(d) : window.__uniapp_x_  
                .postMessageToService(JSON.stringify(d))  
        } else if (o()) {  
            if ("postMessage" === e) {  
                var s = {  
                    data: [n]  
                };  
                return window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessage(s) : window  
                    .__dcloud_weex_.postMessage(JSON.stringify(s))  
            }  
            var w = {  
                type: "WEB_INVOKE_APPSERVICE",  
                args: {  
                    data: i,  
                    webviewIds: t  
                }  
            };  
            window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessageToService(w) : window  
                .__dcloud_weex_.postMessageToService(JSON.stringify(w))  
        } else {  
            if (!window.plus) return window.parent.postMessage({  
                type: "WEB_INVOKE_APPSERVICE",  
                data: i,  
                pageId: ""  
            }, "*");  
            if (0 === t.length) {  
                var u = plus.webview.currentWebview();  
                if (!u) throw new Error("plus.webview.currentWebview() is undefined");  
                var g = u.parent(),  
                    v = "";  
                v = g ? g.id : u.id, t.push(v)  
            }  
            if (plus.webview.getWebviewById("__uniapp__service")) plus.webview.postMessageToUniNView({  
                type: "WEB_INVOKE_APPSERVICE",  
                args: {  
                    data: i,  
                    webviewIds: t  
                }  
            }, "__uniapp__service");  
            else {  
                var c = JSON.stringify(i);  
                plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat(  
                    "WEB_INVOKE_APPSERVICE", '",').concat(c, ",").concat(JSON.stringify(t), ");"))  
            }  
        }  
    },  
    d = {  
        navigateTo: function() {  
            var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},  
                n = e.url;  
            r("navigateTo", {  
                url: encodeURI(n)  
            })  
        },  
        navigateBack: function() {  
            var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},  
                n = e.delta;  
            r("navigateBack", {  
                delta: parseInt(n) || 1  
            })  
        },  
        switchTab: function() {  
            var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},  
                n = e.url;  
            r("switchTab", {  
                url: encodeURI(n)  
            })  
        },  
        reLaunch: function() {  
            var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},  
                n = e.url;  
            r("reLaunch", {  
                url: encodeURI(n)  
            })  
        },  
        redirectTo: function() {  
            var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},  
                n = e.url;  
            r("redirectTo", {  
                url: encodeURI(n)  
            })  
        },  
        getEnv: function(e) {  
            a() ? e({  
                uvue: !0  
            }) : o() ? e({  
                nvue: !0  
            }) : window.plus ? e({  
                plus: !0  
            }) : e({  
                h5: !0  
            })  
        },  
        postMessage: function() {  
            var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};  
            r("postMessage", e.data || {})  
        }  
    },  
    s = /uni-app/i.test(navigator.userAgent),  
    w = /Html5Plus/i.test(navigator.userAgent),  
    u = /complete|loaded|interactive/;  
var g = window.my && navigator.userAgent.indexOf(["t", "n", "e", "i", "l", "C", "y", "a", "p", "i", "l",  
    "A"].reverse().join("")) > -1;  
var v = window.swan && window.swan.webView && /swan/i.test(navigator.userAgent);  
var c = window.qq && window.qq.miniProgram && /QQ/i.test(navigator.userAgent) && /miniProgram/i.test(  
    navigator.userAgent);  
var p = window.tt && window.tt.miniProgram && /toutiaomicroapp/i.test(navigator.userAgent);  
var _ = window.wx && window.wx.miniProgram && /micromessenger/i.test(navigator.userAgent) && /miniProgram/i  
    .test(navigator.userAgent);  
var m = window.qa && /quickapp/i.test(navigator.userAgent);  
var f = window.ks && window.ks.miniProgram && /micromessenger/i.test(navigator.userAgent) && /miniProgram/i  
    .test(navigator.userAgent);  
var l = window.tt && window.tt.miniProgram && /Lark|Feishu/i.test(navigator.userAgent);  
var E = window.jd && window.jd.miniProgram && /jdmp/i.test(navigator.userAgent);  
var x = window.xhs && window.xhs.miniProgram && /xhsminiapp/i.test(navigator.userAgent);  
for (var S, h = function() {  
        window.UniAppJSBridge = !0, document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady", {  
            bubbles: !0,  
            cancelable: !0  
        }))  
    }, y = [function(e) {  
        if (s || w) return window.__uniapp_x_postMessage || window.__uniapp_x_ || window  
            .__dcloud_weex_postMessage || window.__dcloud_weex_ ? document.addEventListener(  
                "DOMContentLoaded", e) : window.plus && u.test(document.readyState) ?  
            setTimeout(e, 0) : document.addEventListener("plusready", e), d  
    }, function(e) {  
        if (_) return window.WeixinJSBridge && window.WeixinJSBridge.invoke ? setTimeout(e, 0) :  
            document.addEventListener("WeixinJSBridgeReady", e), window.wx.miniProgram  
    }, function(e) {  
        if (c) return window.QQJSBridge && window.QQJSBridge.invoke ? setTimeout(e, 0) : document  
            .addEventListener("QQJSBridgeReady", e), window.qq.miniProgram  
    }, function(e) {  
        if (g) {  
            document.addEventListener("DOMContentLoaded", e);  
            var n = window.my;  
            return {  
                navigateTo: n.navigateTo,  
                navigateBack: n.navigateBack,  
                switchTab: n.switchTab,  
                reLaunch: n.reLaunch,  
                redirectTo: n.redirectTo,  
                postMessage: n.postMessage,  
                getEnv: n.getEnv  
            }  
        }  
    }, function(e) {  
        if (v) return document.addEventListener("DOMContentLoaded", e), window.swan.webView  
    }, function(e) {  
        if (p) return document.addEventListener("DOMContentLoaded", e), window.tt.miniProgram  
    }, function(e) {  
        if (m) {  
            window.QaJSBridge && window.QaJSBridge.invoke ? setTimeout(e, 0) : document  
                .addEventListener("QaJSBridgeReady", e);  
            var n = window.qa;  
            return {  
                navigateTo: n.navigateTo,  
                navigateBack: n.navigateBack,  
                switchTab: n.switchTab,  
                reLaunch: n.reLaunch,  
                redirectTo: n.redirectTo,  
                postMessage: n.postMessage,  
                getEnv: n.getEnv  
            }  
        }  
    }, function(e) {  
        if (f) return window.WeixinJSBridge && window.WeixinJSBridge.invoke ? setTimeout(e, 0) :  
            document.addEventListener("WeixinJSBridgeReady", e), window.ks.miniProgram  
    }, function(e) {  
        if (l) return document.addEventListener("DOMContentLoaded", e), window.tt.miniProgram  
    }, function(e) {  
        if (E) return window.JDJSBridgeReady && window.JDJSBridgeReady.invoke ? setTimeout(e, 0) :  
            document.addEventListener("JDJSBridgeReady", e), window.jd.miniProgram  
    }, function(e) {  
        if (x) return window.xhs.miniProgram  
    }, function(e) {  
        return document.addEventListener("DOMContentLoaded", e), d  
    }], M = 0; M < y.length && !(S = y[M](h)); M++);  
S || (S = {});  
var P = "undefined" != typeof y_uni ? y_uni : {};  
if (!P.navigateTo)  
    for (var b in S) i(S, b) && (P[b] = S[b]);  
return P.webView = S, P  

}));
module.exports = y_uni;

用这段代码替换作者的库

这是一个典型的跨平台WebView通信兼容性问题。在鸿蒙Next的WebView中,通信机制可能与Android/iOS存在差异。

核心问题在于鸿蒙Next的WebView对postMessage的实现可能不完全兼容标准Web API。建议尝试以下解决方案:

  1. 使用uni-app官方通信方案
// H5页面发送消息
uni.postMessage({
  data: {
    action: 'message',
    data: 'hellosam'
  }
});

// WebView页面接收
<web-view @message="onMessage"></web-view>
onMessage(e) {
  console.log(e.detail.data);
}
  1. 检查鸿蒙WebView配置: 确保WebView组件启用了JavaScript支持和消息传递:
<web-view :webview-styles="webviewStyles"></web-view>
webviewStyles: {
  progress: { color: '#00FF00' }
}
  1. 使用原生API降级方案
// 检测环境并选择通信方式
if (window.uni) {
  uni.postMessage({ data: yourData });
} else if (window.webkit && window.webkit.messageHandlers) {
  // iOS WebView
  window.webkit.messageHandlers.xxx.postMessage(yourData);
} else {
  // 鸿蒙或其他环境
  window.parent.postMessage(yourData, '*');
}
回到顶部