官网介绍: 在webview内部的网页中调用
window.postMessage
方法时可以触发此属性对应的函数,从而实现网页和RN之间的数据交换。 设置此属性的同时会在webview中注入一个postMessage
的全局函数并覆盖可能已经存在的同名实现。
网页端的window.postMessage
只发送一个参数data
,此参数封装在RN端的event对象中,即event.nativeEvent.data
。data
只能是一个字符串。
先上图,点击webview中的按钮,获取到html页面中postMessage的数据

使用:
1.rn端
- 添加onMessage 属性
onMessage = (event) => {
//webview中的html页面传过来的的数据在event.nativeEvent.data上
console.log(event.nativeEvent.data);
}
<WebView onMessage={this.onMessage} source={{ uri: url }}/>
2.html(js)端
- window.postMessage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="btn">点击我</button>
</body>
<script>
function test() {
console.log('只能传递一个字符串类型的参数');
if(!!window.postMessage) {
window.postMessage('只能传递一个字符串类型的参数');
}
}
document.getElementById("btn").onclick = function() {
test();
}
</script>
</html>
网友评论