uniapp 如何跟内嵌web-view交互

废话开篇:不同的语言运行环境由于业务的相交有时候会进行交互,比如状态、事件的交互,这里简单记录一下 uniapp 如何跟内嵌 web-view 交互

一、代码环境

<template>
 <view id="container">
 <web-view style="width: 100%;height: 100%;" @message="message" :src="url"></web-view>
 </view>
</template>

这里是很简单的一个 vue 页面内容,其中 web-view 是当前页面内嵌的网页加载组件,这里捆绑了一个 url 地址,那么,接下来就是将 url 地址加载的 html 页面与 uniapp 内部的 vue 文件进行交互。

二、uniapp 内向 web 组件发起交互

方法一、利用 html 页面的hash(#号)

vue 触发事件

let info = {name:'hello'}
this.url = 'http://www.****.com' + '#' + JSON.stringify(info)

这里用 # 号链接后面需要传的数据。

html 页面接受事件

function registWindowHashEvent(){
 window.addEventListener('hashchange',()=>{
 const value = location.hash
 })
}

注册监听 hashchange 变化事件,当 vue 页面的 url 不断变化的时候,会触发这里的回调以达到交互的目的。

方法二、直接调用 html 定义方法

vue 触发事件

首先需要获取 vue 页面下的 webview 组件对象。

data() {
 return {
 url:'',
 currentWebview:null,
 };
}

data 里面添加 currentWebview 属性。

mounted() {
 const self = this;
 self.currentWebview = self.$scope.$getAppWebview().children()
}

在挂载里获取要交互的 webview 对象。

const self = this;
let info = {name:'hello'}
self.currentWebview.evalJS(`uniEvent(${JSON.stringify(info)})`);

这里直接利用 webview 对象运行约定好的方法,比如:uniEvent

html 页面接受事件

function addUniEvenPassthrough(){
 window.uniEvent= function(info) {
 }
}

window 对象上添加 uniEvent 事件。

有 uniapp 直接通过对象的方式调用方法以达到交互的目的。

三、 web 内向 uniapp 组件发起交互

html 触发事件

首先,先下载 uni.webview.js ,可以下载后保存到本地, uni.webview.js 可以实现由 webviewvue 页面发送事件。

var uniBridgeIsInitFinished = false;
function registUniBridgeIsInitFinishEvent(){
 document.addEventListener('UniAppJSBridgeReady', function() {
 uniBridgeIsInitFinished = true;
 });
}

定义一个变量,保存 uni.webview.js 初始化完成状态。

注册 registUniBridgeIsInitFinishEvent 来监听 uni.webview.js 是否初始化完成。

//发送消息给uni
function sendInfoToUni(info){
 if(uniBridgeIsInitFinished == true){
 uni.postMessage({
 data: {
 order: JSON.stringify(info)
 }
 });
 }
}

直接通过 uni.postMessagevue 页面传递数据。

vue 页面接受事件

<template>
 <view id="container">
 <web-view style="width: 100%;height: 100%;" @message="message" :src="url"></web-view>
 </view>
</template>

这里给 web-view 绑定 message 方法。

methods: {
 message(info){
 }
}

这样在 message 方法里就直接可以获取到 html 页面穿过来的 info 参数了。

四、总结与思考

通过上面的方法就能实现 uniapp 跟内嵌 web-view 交互。当有些业务或者vue 环境不能实现某些功能的时候,便需要理由 web-view 去展示,实现 uniapp 跟内嵌 web-view 交互能让开发更加灵活。个人随笔,大佬勿笑[抱拳][抱拳][抱拳]

作者:头疼脑胀的代码搬运工

%s 个评论

要回复文章请先登录注册