h5網(wǎng)頁向react-native發(fā)消息
- 網(wǎng)頁事件中發(fā)送消息
window.postMessage('網(wǎng)頁向rn發(fā)送的消息');
-
react-native
中接收消息webview
實(shí)現(xiàn)onMessage={this.handleMessage}
方法,該方法中的e.nativeEvent.data
就是網(wǎng)頁傳過來的消息handleMessage(e) {console.log(e.nativeEvent.data)}
- 注意這里的傳至只能是
string
react-native網(wǎng)頁向h5發(fā)消息
- 首先
webview
綁定ref={webview => this.webview = webview}
- 自定義一個(gè)點(diǎn)擊事件窿撬,點(diǎn)擊時(shí)執(zhí)行
this.webview.postMessage('rn向網(wǎng)頁發(fā)送的消息');
- 網(wǎng)頁加在時(shí)進(jìn)行監(jiān)聽
e.data
就為rn發(fā)送過來的消息
window.onload = function() {
document.addEventListener('message', function(e) {
console.log(e.data)
});
遇到的一個(gè)小問題Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined.
const patchPostMessageFunction = function() {
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
};
const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';
- 在
webview
加載時(shí)注入<WebView injectedJavaScript={patchPostMessageJsCode}/>
就可以解決這個(gè)問題
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者