uniapp中app與webview的通訊代碼示例
1.app->webview
app發(fā)送
此處使用evalJS方法
<template> <web-view src="../../static/chat2.html"></web-view> <button @click="chatRes">生成評估總結(jié)</button> </template> <script> methods:{ chatRes() { let str="需要發(fā)送的信息" const _funName = 'msgFromUniapp' const _data = { msg: str }; const currentWebview = this.$scope.$getAppWebview().children()[0]; currentWebview.evalJS(`${_funName}(${JSON.stringify(_data)})`); }, } </script>
webview接收
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>評測記錄</title> </head> <body> </body> <script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script> <script> let msg='' window.msgFromUniapp = function(arg) { msg=arg.msg console.log(msg); } </script> </html>
2.webview->app
webview發(fā)送
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>評測記錄</title> </head> <body> </body> <script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script> <script> const sendMsg = () => { let str="待發(fā)送的信息" uni.postMessage({ data: { msgContent:str } }) } </script> </html>
app接收
<template> <web-view @message="handlerMessage" src="../../static/chat2.html"></web-view> </template> <script> methods:{ handlerMessage(event) { console.log(event.detail.data[0]) }, } </script>
3.踩坑記錄
webview使用uni.postMessage發(fā)送消息給app時報uni.postMessage is not a function
解決方案
- 取消引入官方庫uni-webview-js
- 改寫uni為y_uni,調(diào)用y_uni.postMessage
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>評測記錄</title> </head> <body> </body> <script> let y_uni; ! function(e, n) { y_uni = n(); return console.log(4777) 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 r() { return window.__dcloud_weex_postMessage || window.__dcloud_weex_ } var o = function(e, n) { var i = { options: { timestamp: +new Date }, name: e, arg: n }; if (r()) { if ("postMessage" === e) { var o = { data: [n] }; return window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessage(o) : window .__dcloud_weex_.postMessage(JSON.stringify(o)) } var a = { type: "WEB_INVOKE_APPSERVICE", args: { data: i, webviewIds: t } }; window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessageToService(a) : window .__dcloud_weex_.postMessageToService(JSON.stringify(a)) } if (!window.plus) return window.parent.postMessage({ type: "WEB_INVOKE_APPSERVICE", data: i, pageId: "" }, "*"); if (0 === t.length) { var d = plus.webview.currentWebview(); if (!d) throw new Error("plus.webview.currentWebview() is undefined"); var s = d.parent(), w = ""; w = s ? s.id : d.id, t.push(w) } if (plus.webview.getWebviewById("__uniapp__service")) plus.webview.postMessageToUniNView({ type: "WEB_INVOKE_APPSERVICE", args: { data: i, webviewIds: t } }, "__uniapp__service"); else { var u = JSON.stringify(i); plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat( "WEB_INVOKE_APPSERVICE", '",').concat(u, ",").concat(JSON.stringify(t), ");")) } }, a = { navigateTo: function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, n = e.url; o("navigateTo", { url: encodeURI(n) }) }, navigateBack: function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, n = e.delta; o("navigateBack", { delta: parseInt(n) || 1 }) }, switchTab: function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, n = e.url; o("switchTab", { url: encodeURI(n) }) }, reLaunch: function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, n = e.url; o("reLaunch", { url: encodeURI(n) }) }, redirectTo: function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, n = e.url; o("redirectTo", { url: encodeURI(n) }) }, getEnv: function(e) { r() ? e({ nvue: !0 }) : window.plus ? e({ plus: !0 }) : e({ h5: !0 }) }, postMessage: function() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; o("postMessage", e.data || {}) } }, d = /uni-app/i.test(navigator.userAgent), s = /Html5Plus/i.test(navigator.userAgent), w = /complete|loaded|interactive/; var u = window.my && navigator.userAgent.indexOf(["t", "n", "e", "i", "l", "C", "y", "a", "p", "i", "l", "A" ].reverse().join("")) > -1; var g = window.swan && window.swan.webView && /swan/i.test(navigator.userAgent); var v = window.qq && window.qq.miniProgram && /QQ/i.test(navigator.userAgent) && /miniProgram/i.test( navigator.userAgent); var c = window.tt && window.tt.miniProgram && /toutiaomicroapp/i.test(navigator.userAgent); var m = window.wx && window.wx.miniProgram && /micromessenger/i.test(navigator.userAgent) && /miniProgram/i .test(navigator.userAgent); var p = 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 _ = window.jd && window.jd.miniProgram && /micromessenger/i.test(navigator.userAgent) && /miniProgram/i .test(navigator.userAgent); var E = window.xhs && window.xhs.miniProgram && /xhsminiapp/i.test(navigator.userAgent); for (var h, P = function() { window.UniAppJSBridge = !0, document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady", { bubbles: !0, cancelable: !0 })) }, b = [function(e) { if (d || s) return window.__dcloud_weex_postMessage || window.__dcloud_weex_ ? document .addEventListener("DOMContentLoaded", e) : window.plus && w.test(document .readyState) ? setTimeout(e, 0) : document.addEventListener("plusready", e), a }, function(e) { if (m) return window.WeixinJSBridge && window.WeixinJSBridge.invoke ? setTimeout(e, 0) : document.addEventListener("WeixinJSBridgeReady", e), window.wx.miniProgram }, function(e) { if (v) return window.QQJSBridge && window.QQJSBridge.invoke ? setTimeout(e, 0) : document .addEventListener("QQJSBridgeReady", e), window.qq.miniProgram }, function(e) { if (u) { 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 (g) return document.addEventListener("DOMContentLoaded", e), window.swan.webView }, function(e) { if (c) return document.addEventListener("DOMContentLoaded", e), window.tt.miniProgram }, function(e) { if (p) { 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 (_) return window.JDJSBridgeReady && window.JDJSBridgeReady.invoke ? setTimeout(e, 0) : document.addEventListener("JDJSBridgeReady", e), window.jd.miniProgram }, function(e) { if (E) return window.xhs.miniProgram }, function(e) { return document.addEventListener("DOMContentLoaded", e), a }], y = 0; y < b.length && !(h = b[y](P)); y++); h || (h = {}); var B = "undefined" != typeof y_uni ? y_uni : {}; if (!B.navigateTo) for (var S in h) i(h, S) && (B[S] = h[S]); return B.webView = h, B })); const sendMsg = async () => { let str="待發(fā)送的信息" y_uni.postMessage({ data: { msgContent:str } }) } </script> </html>
總結(jié)
到此這篇關(guān)于uniapp中app與webview通訊的文章就介紹到這了,更多相關(guān)uniapp app與webview通訊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue使用elementUI分頁如何實現(xiàn)切換頁面時返回頁面頂部
這篇文章主要介紹了vue使用elementUI分頁如何實現(xiàn)切換頁面時返回頁面頂部,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08如何使用vue slot創(chuàng)建一個模態(tài)框的實例代碼
這篇文章主要介紹了如何使用vue slot創(chuàng)建一個模態(tài)框,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05解決Vue2跨域報錯AxiosError?net::ERR_FAILED、?Network?Error、ERR_N
這篇文章主要給大家介紹了關(guān)于解決Vue2跨域報錯AxiosError?net::ERR_FAILED、?Network?Error、ERR_NETWORK的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11vue點擊導(dǎo)航頁面實現(xiàn)自動滾動到特定位置
這篇文章主要介紹了vue點擊導(dǎo)航頁面實現(xiàn)自動滾動到特定位置方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03vue數(shù)據(jù)更新但視圖(DOM)不刷新的幾種解決辦法
這篇文章主要給大家介紹了關(guān)于vue數(shù)據(jù)更新但視圖(DOM)不刷新的幾種解決辦法,我們在開發(fā)過程中經(jīng)常會碰到數(shù)據(jù)更新,但是視圖并未改變的情況,需要的朋友可以參考下2023-08-08