react-native webview 與js通信

官網(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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容