React-Native Webview 和H5交互的兩種方式

React-Native WebView 和H5交互有兩種方式:

方式1:RN Webview 向H5注入JS

此方式可作為Webview向H5端傳遞數(shù)據(jù)。
RN Webview 有以下屬性,可以注入一段js,然后在相應(yīng)的時(shí)間調(diào)用。
injectedJavaScript 設(shè)置 js 字符串,在網(wǎng)頁(yè)加載之前注入的一段 JS 代碼。

類型 必填
string

思路:通過(guò)injectedJavaScript 注入JS ,在H5頁(yè)面加載之后立即執(zhí)行。相當(dāng)于webview端主動(dòng)調(diào)用H5的方法。
這里有個(gè)注意點(diǎn),injectedJavaScript注入的必須是js。注入的內(nèi)容可以是方法實(shí)現(xiàn),也可以是方法名字
需要說(shuō)明
1.其實(shí)注入函數(shù)名的時(shí)候,實(shí)際上注入的仍然是函數(shù)實(shí)現(xiàn)
2.當(dāng)注入js方法名需要傳遞參數(shù)的時(shí)候,可提前將函數(shù)名作為字符串,函數(shù)參數(shù)作為變量,生成一個(gè)字符串,然后將此字符串注入。

H5端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onClick="hhh(abc)" style="margin-top: 100px;" id="hhhh">hhhh</button>
<button id="rrrrrr">rrrrrr</button>
<script>


alert(1111);
    function hhh(text) {
        var hideButon=  document.getElementById('rrrrrr')
//            .style.display = 'none';

//        hideButon.style.display='none';

        hideButon.innerHTML=text;
    }


    function yyy(text) {
//        var hideButon=
            document.getElementById('hhhh').innerHTML="1111111111";
//            .style.display = 'none';

        alert(text);

//        hideButon.innerHTML="text";
    }



</script>

</body>
</html>

RN端

    render() {
        let text = this.props.navigation.state.params.authInfo;
        let text1 = `yyy('${text}')`;
        console.log(text1);
        return (
            <View
                style={{flex: 1, backgroundColor: 'white', marginBottom: SAFE_AREA_BOTTOM_HEIGHT}}>
                <WebView style={{flex: 1}}
                         ref='webView'
                    // source={{uri: this.props.navigation.state.params.url}}
                         injectedJavaScript={`${text1}`}

                         source={{
                             html: '<body>\n' +
                             '<button onClick="hhh()" style="margin-top: 100px;" id="hhhh">hhhh</button>\n' +
                             '<button id="rrrrrr">rrrrrr</button>\n' +
                             '<script>\n' +
                             '\n' +
                             '\n' +
                             '    function hhh(text) {\n' +
                             '        var hideButon=  document.getElementById(\'rrrrrr\')\n' +
                             '//            .style.display = \'none\';\n' +
                             '\n' +
                             '//        hideButon.style.display=\'none\';\n' +
                             '\n' +
                             '        hideButon.innerHTML="text";\n' +
                             '    }\n' +
                             '\n' +
                             '\n' +
                             '    function yyy(text) {\n' +
                             '//        var hideButon=\n' +
                             '            document.getElementById(\'hhhh\').innerHTML=text;\n' +
                             '//            .style.display = \'none\';\n' +
                             '\n' +
                             '        alert(text);\n' +
                             '\n' +
                             '        hideButon.innerHTML="text";\n' +
                             '    }\n' +
                             '\n' +
                             '\n' +
                             '\n' +
                             '</script>\n' +
                             '\n' +
                             '</body>'
                         }}

                    // onLoadEnd={() => {
                    //      this.refs.webView.postMessage(this.props.navigation.state.params.authInfo);
                    // }}
                >
                </WebView>
            </View>
        );
    }

這種方式和OC中WKWebView注入JS的原理基本一致。

方式2:Webview 和 H5 相互發(fā)送監(jiān)聽(tīng)消息

該方式可雙向發(fā)送數(shù)據(jù)信息。

(1)RN端向H5發(fā)送消息

首先Webview綁定ref={webview => this.webview = webview}

onLoadEnd={() => {
 this.refs.webView.postMessage('RN向H5發(fā)送的消息');
 }}

也可可在其他任意地方獲取webview,執(zhí)行this.webview.postMessage('RN向H5發(fā)送的消息');
H5在加載的時(shí)候注冊(cè)監(jiān)聽(tīng)。

H5 監(jiān)聽(tīng)message 注意這個(gè)監(jiān)聽(tīng)的名字只能叫message。

in Android

window.onload = function() {
document.addEventListener("message", function(event) {
       alert("This is a Entry Point Working in android");
       init(event.data)
  });
}

in iOS

window.onload = function() {
     window.addEventListener("message", function(event) {
       alert("This is a Entry Point Working in iOS");
       init(event.data)
  });
 }


(2)H5向RN發(fā)送消息

RN Webview onMessage 屬性

在 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è)字符串。

webview 組件 在被官方放棄之后,react-native-webview 作為替換。react-native-webview 5.0 之后需要注入js

https://github.com/react-native-community/react-native-webview/releases/tag/v5.0.0
需要注入以下這段js 用以替換window.postMessage. H5 使用方法不變。

const injectedJavascript = `(function() {
  window.postMessage = function(data) {
    window.ReactNativeWebView.postMessage(data);
  };
})()`;
類型 必填
function

實(shí)現(xiàn)過(guò)程:

H5發(fā)送消息,此時(shí)只能傳遞string類型

window.postMessage('網(wǎng)頁(yè)向rn發(fā)送的消息');

react-native中接收消息

onMessage={(event) => {console.log(event.nativeEvent.data);}}
最后編輯于
?著作權(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)容

  • 前言 基于React-Native0.41及0.25兩個(gè)版本來(lái)分析 公司項(xiàng)目基于ReactNative開(kāi)發(fā),最近有...
    jiaming_閱讀 29,762評(píng)論 12 23
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,286評(píng)論 8 265
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,694評(píng)論 1 32
  • 用兩張圖告訴你,為什么你的 App 會(huì)卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 14,144評(píng)論 2 59
  • 所謂失敗,應(yīng)該是指沒(méi)有堅(jiān)持本該有的堅(jiān)持,而讓一些無(wú)謂的瑣碎打磨掉對(duì)生活的希望和期待。所謂成功,應(yīng)該就是目光同腳步一...
    M_152閱讀 201評(píng)論 0 0

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