官網(wǎng)介紹: 在webview內(nèi)部的網(wǎng)頁(yè)中調(diào)用
window.postMessage方法時(shí)可以觸發(fā)此屬性對(duì)應(yīng)的函數(shù),從而實(shí)現(xiàn)網(wǎng)頁(yè)和RN之間的數(shù)據(jù)交換。 設(shè)置此屬性的同時(shí)會(huì)在webview中注入一個(gè)postMessage的全局函數(shù)并覆蓋可能已經(jīng)存在的同名實(shí)現(xiàn)。
網(wǎng)頁(yè)端的window.postMessage只發(fā)送一個(gè)參數(shù)data,此參數(shù)封裝在RN端的event對(duì)象中,即event.nativeEvent.data。data只能是一個(gè)字符串。
先上圖,點(diǎn)擊webview中的按鈕,獲取到html頁(yè)面中postMessage的數(shù)據(jù)

image.png
使用:
1.rn端
- 添加onMessage 屬性
onMessage = (event) => {
//webview中的html頁(yè)面?zhèn)鬟^(guò)來(lái)的的數(shù)據(jù)在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">點(diǎn)擊我</button>
</body>
<script>
function test() {
console.log('只能傳遞一個(gè)字符串類型的參數(shù)');
if(!!window.postMessage) {
window.postMessage('只能傳遞一個(gè)字符串類型的參數(shù)');
}
}
document.getElementById("btn").onclick = function() {
test();
}
</script>
</html>