Uniapp中App与H5交互

915 阅读2分钟

Uniapp开发的App要与Uniapp开发的H5进行交互

Uniapp进行数据交互的话是使用了Unaipp官方文档当中的web-view,但是官方文档当中的说明也不是很通俗易懂,之后就去网上找了好久,也试了很多次,终于实现了App与H5的交互。

web-view

首先呢web-view是一个 web 浏览器组件,可以用来承载网页的容器,会自动铺满整个页面,nvue 使用需要手动指定宽高。在web-view中的src当中放入H5页面的链接即可。
各小程序平台,web-view 加载的 url 需要在后台配置域名白名单,包括内部再次 iframe 内嵌的其他 url 以下是官方文档当中的代码片段,官网链接[:](web-view | uni-app官网 (dcloud.net.cn))

<template>
	<view>
		<web-view :webview-styles="webviewStyles" src="https://uniapp.dcloud.io/static/web-view.html"></web-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				}
			}
		}
	}
</script>

<style>

</style>

在Uniapp当中呢,uni.postMessage是用来接收H5传来的数据的,这个可以查看Uniapp官方文档自行解决,而在交互当中让我们为难的无非就是H5如何向App传递数据和接受App传来的数据以及App如何向H5传递数据

H5向App传递数据

在uniapp项目下的static中新建一个uni_webview.js然后将下面的代码复制进去

! function(e, n) {
	"object" == typeof exports && "undefined" != typeof module ? module.exports = n() : "function" == typeof define &&
		define.amd ? define(n) : (e = e || self).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 t(e, t) {
		return n.call(e, t)
	}
	var i = [],
		a = function(e, n) {
			var t = {
				options: {
					timestamp: +new Date
				},
				name: e,
				arg: n
			};
			if (window.__dcloud_weex_postMessage || window.__dcloud_weex_) {
				if ("postMessage" === e) {
					var a = {
						data: [n]
					};
					return window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessage(a) : window
						.__dcloud_weex_.postMessage(JSON.stringify(a))
				}
				var o = {
					type: "WEB_INVOKE_APPSERVICE",
					args: {
						data: t,
						webviewIds: i
					}
				};
				window.__dcloud_weex_postMessage ? window.__dcloud_weex_postMessageToService(o) : window
					.__dcloud_weex_.postMessageToService(JSON.stringify(o))
			}
			if (!window.plus) return window.parent.postMessage({
				type: "WEB_INVOKE_APPSERVICE",
				data: t,
				pageId: ""
			}, "*");
			if (0 === i.length) {
				var r = plus.webview.currentWebview();
				if (!r) throw new Error("plus.webview.currentWebview() is undefined");
				var d = r.parent(),
					s = "";
				s = d ? d.id : r.id, i.push(s)
			}
			if (plus.webview.getWebviewById("__uniapp__service")) plus.webview.postMessageToUniNView({
				type: "WEB_INVOKE_APPSERVICE",
				args: {
					data: t,
					webviewIds: i
				}
			}, "__uniapp__service");
			else {
				var w = JSON.stringify(t);
				plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat(
					"WEB_INVOKE_APPSERVICE", '",').concat(w, ",").concat(JSON.stringify(i), ");"))
			}
		},
		o = {
			navigateTo: function() {
				var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
					n = e.url;
				a("navigateTo", {
					url: encodeURI(n)
				})
			},
			navigateBack: function() {
				var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
					n = e.delta;
				a("navigateBack", {
					delta: parseInt(n) || 1
				})
			},
			switchTab: function() {
				var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
					n = e.url;
				a("switchTab", {
					url: encodeURI(n)
				})
			},
			reLaunch: function() {
				var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
					n = e.url;
				a("reLaunch", {
					url: encodeURI(n)
				})
			},
			redirectTo: function() {
				var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
					n = e.url;
				a("redirectTo", {
					url: encodeURI(n)
				})
			},
			getEnv: function(e) {
				window.plus ? e({
					plus: !0
				}) : e({
					h5: !0
				})
			},
			postMessage: function() {
				var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
				a("postMessage", e.data || {})
			}
		},
		r = /uni-app/i.test(navigator.userAgent),
		d = /Html5Plus/i.test(navigator.userAgent),
		s = /complete|loaded|interactive/;
	var w = window.my && navigator.userAgent.indexOf("AlipayClient") > -1;
	var u = 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 g = window.tt && window.tt.miniProgram && /toutiaomicroapp/i.test(navigator.userAgent);
	var v = window.wx && window.wx.miniProgram && /micromessenger/i.test(navigator.userAgent) && /miniProgram/i
		.test(navigator.userAgent);
	var p = window.qa && /quickapp/i.test(navigator.userAgent);
	for (var l, _ = function() {
			window.UniAppJSBridge = !0, document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady", {
				bubbles: !0,
				cancelable: !0
			}))
		}, f = [function(e) {
			if (r || d) return window.__dcloud_weex_postMessage || window.__dcloud_weex_ ? document
				.addEventListener("DOMContentLoaded", e) : window.plus && s.test(document
					.readyState) ? setTimeout(e, 0) : document.addEventListener("plusready", e), o
		}, function(e) {
			if (v) 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 (w) {
				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 (u) return document.addEventListener("DOMContentLoaded", e), window.swan.webView
		}, function(e) {
			if (g) 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) {
			return document.addEventListener("DOMContentLoaded", e), o
		}], m = 0; m < f.length && !(l = f[m](_)); m++);
	l || (l = {});
	var E = "undefined" != typeof uni ? uni : {};
	if (!E.navigateTo)
		for (var b in l) t(l, b) && (E[b] = l[b]);
	return E.webView = l, E
}));

然后再在main.js当中全局引入这个js文件

import * as uni from '@/static/uni_webview.js'

document.addEventListener("UniAppJSBridgeReady", function(e) {
	console.log(e)
	Vue.prototype.myUni = uni
});

之后我们就可以在页面当中去使用它来实现数据交互了~

<template>
	<view>
            <button @click="post">H5向App传递数据</button>
	</view>
</template>

<script>
export default {
    data() {
        return {
				
               }
	   },
           onLoad(){
               this.get()
           },
          methods:{
                post(){
                     this.myUni.webView.postMessage({
                          //data当中是H5向App的传递数据
                          data: {},
		           });
                    },
                    get(){
                        接收app传递来的数据
				window.postJS = function(msg) {
                                    //msg是App传递过来的数据
                                    console.log(msg)
                                }
                    }
        }
}
</script>

<style>

</style>