0

反应本机版本:0.60

使用的库:react-native-webview(版本:9.0.1)

问题

当我将 postMessage ( this.webView.postMessage('somedata')) 从我的 react-native 事件处理程序发送到 webview 时,不会触发 onMessage。但是 onMessage 确实会在 webview 发送的事件上触发。

尝试的解决方案

添加了 document.eventListener 和 window.eventListener。当我从 react-native 发布消息时,仍然不会触发 onMessage。

任何帮助将不胜感激。

代码

  // On Click, the following function will run
  
  _sendPostMessage = () => {
    //data sent to webview
    this.webView.postMessage("getAuthToken");
  }
  
  // Inside render() function
  
<WebView
  ref={(webView) => this.webView = webView}
  style={styles.webView}
  source={{ uri: event.ticket_form_url, headers: headers }}
  injectedJavaScript={jsCode}
  onMessage={this.onMessage}
  renderLoading={this._renderActivityIndicator}
  startInLoadingState={true}
/>

// Injected javscript code below

    var jsCode = `
      (function() {
        window.postMessage = function(data) {
          window.ReactNativeWebView.postMessage(data);
        };
      })()
      (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;
      })();

      window.addEventListener("message", function(event) {
        var uat = ''

        if (window.userAuthenticationToken) {
          uat = window.userAuthenticationToken()
        }

        window.postMessage('setAuthToken,' + uat)
      });

      document.addEventListener("message", function(event) {
        var uat = ''

        if (window.userAuthenticationToken) {
          uat = window.userAuthenticationToken()
        }

        window.postMessage('setAuthToken,' + uat)
      });

      `;

// onMessage

  onMessage = (event) => {
    //data received from webview
    console.log('Reached onMessage', event.nativeEvent.data);
    var response = event.nativeEvent.data
    var data = response.split(',')
 }

  
  

4

1 回答 1

0

您好,您必须使用 post message 作为注入的Javascript。例如,

<WebView
    source={{ uri:'https://stackoverflow.com' }}
    injectedJavaScript="window.ReactNativeWebView.postMessage(document.title)"
    onMessage={event => setTitle(event.nativeEvent.data)}
/>

您可以将此包用于美容 UI 的 webview。 https://github.com/ilkerkesici/react-native-beauty-webview

于 2020-07-12T14:38:40.813 回答