【问题标题】:Howto solve postMessage from WebView to React Native does not work for Android如何解决从 WebView 到 React Native 的 postMessage 不适用于 Android
【发布时间】:2018-05-11 02:33:49
【问题描述】:

这个基本的 postMessage 示例适用于 IOS,但不适用于 Android

Android 上的 React Native 应用无法接收到注入 WebView 的 js 代码(const simple)发送的 post 消息。

import React, {Component} from 'react';
import {
    WebView
} from 'react-native';

export default class App extends Component<{}> {
    render() {
        const simple = function() { window.postMessage('my message from Webview to RN');}
        const postMessageCode = '(' + String(simple) + ')();';
        return (
            <WebView
                source={{uri: 'https://github.com/facebook/react-native'}}
                injectedJavaScript={postMessageCode}
                onMessage={this.onWebViewMessage}
            />
        );
    }

    onWebViewMessage(event) {
        alert(event);
    }
}

这已经过测试:

  • react-native-cli: 2.0.1
  • 反应原生:0.50.4

开启: - Android 模拟器版本 26.0.0-3833124,Android 7.1.1,API 25 - Android原生设备ONE E1005(一加X),Android版本6.0.1,API 23

谁能够让 postMessage 在 Android 设备/模拟器上运行(WebView --> RN),或者认为他们知道如何?

【问题讨论】:

    标签: android react-native


    【解决方案1】:

    改用 WebView ref postMessage

    import React, {Component} from 'react';
    import {
        WebView
    } from 'react-native';
    
    export default class App extends Component<{}> {
        sendMessage = () => { 
          this.webViewRef.postMessage('my message from Webview to RN');
        }
    
        render() {
            return (
                <WebView
                    source={{uri: 'theURL'}}
                    ref={(ref) => { this.webViewRef = ref }}
                    onMessage={this.onWebViewMessage}
                />
            );
        }
    
        onWebViewMessage(event) {
            alert(event);
        }
    }
    

    【讨论】:

    • 你好胡安。感谢你的回复。您是否按照问题中给出的规格尝试过这个?
    【解决方案2】:

    我遇到了同样的问题。在 React Native 将侦听器附加到 postMessage 时,Android 浏览器似乎存在延迟。见https://github.com/facebook/react-native/issues/11594

    我在我的网页上使用这个小助手来解决它:

    var message = 'some message string';
    
    window.parent.postMessage(message,"*"); 
    
    function whenRNPostMessageReady(cb) {
        if (postMessage.length === 1) cb();
        else setTimeout(function() { whenRNPostMessageReady(cb) }, 100);
    }
    whenRNPostMessageReady(function() {
        //react native accepts strings only
        window.parent.postMessage(JSON.stringify(message),"*");
    });
    

    【讨论】:

      猜你喜欢
      • 2017-04-30
      • 2021-09-20
      • 1970-01-01
      • 2020-07-03
      • 2022-11-23
      • 2021-09-26
      • 2020-03-25
      • 2017-06-08
      • 2020-08-18
      相关资源
      最近更新 更多