uniapp web-view 之间的通讯

uniapp web-view 之间的通讯大概分为 App <=> H5 之间的通讯、 H5 <=> H5 之间的通讯

下面我们就针对这两种方式来实现吧

一、App <=> H5 之间的通讯

传递时 H5 需要使用到第三方插件 (下载地址: http://download.tiandingyu.cn/webview.js)

1、App => H5 传递信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- App端发送消息 -->
<template>
<web-view src="http://localhost:8080" ref="webView"> </web-view>
</template>
<script>
export default{
create(){
let current = this.$scope.$getAppWebview();
let webView = current.children()[0];
<!-- getUniAppMessage为H5端的函数 -->
webView.evalJS(`getUniAppMessage('我是App, 你收到消息了吗?')`);
}
}
</script>

<!-- H5端接收消息 -->
window.getUniAppMessage = function (event) {
console.log(event) // 我是App, 你收到消息了吗?
};

2、H5 => App 传递信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- H5端发送消息 -->
import uniwebview from './webview.js';

uniwebview.webView.postMessage({
data: {
message: "我是H5, 你收到消息了吗?"
}
});

<!-- App端接收消息 -->
<template>
<web-view src="http://localhost:8080" ref="webView" @message="handleMessage"> </web-view>
</template>
<script>
export default{
methods:{
handleMessage(msg) {
console.log(msg.detail.data[0].message); // 我是H5, 你收到消息了吗?
},
},
}
</script>

二、H5 <=> H5 之间的通讯

1、H5父项目 => H5子项目 传递信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 父项目发送消息 -->
<template>
<web-view src="http://localhost:8080" ref="webView"></web-view>
</template>
<script>
export default{
create(){
let iframeWindow: any = document.getElementsByTagName('iframe')[0];
iframeWindow.onload = () => {
window.frames[0].postMessage("我是父项目,你收到消息了吗?", '*');
};
}
}
</script>

<!-- 子项目接收消息 -->
window.addEventListener('message',(event) => {
console.log(event.data); // 我是父项目,你收到消息了吗?
},
false
);

2、H5子项目 => H5父项目 传递信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 子项目发送消息 -->
window.addEventListener('message',(event) => {
event.source.postMessage('我是子项目,你收到消息了吗?', '*')
},
false
);

<!-- 父项目接收消息 -->
<template>
<web-view src="http://localhost:8080" ref="webView"></web-view>
</template>
<script>
export default{
create(){
window.addEventListener('message',(event) => {
console.log(event.data); // 我是子项目,你收到消息了吗?
},
false
);
}
</script>