wheatandcatの開発ブログ

React Nativeで開発しているペペロミア & memoirの技術系記事を投稿してます

Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined.

今日はハマったバグの話、忘れた頃に同じことで引っかかりそうなので、ここに残しておきます

内容

React Nativeで画面で複数のWebViewに対してonMessageで値のやり取りをしていたら、↓のエラーが発生

Setting onMessage on a WebView overrides existing values of window.postMessage,
but a previous value was defined.

ググったら、↓がヒット

github.com

対応コード

issuesの通り↓こんな感じで回避できた

import React, { Component } from "react";
import { Platform, Alert, WebView } from "react-native";
import Page from "./Page";

// issues: https://github.com/facebook/react-native/issues/10865
const patchPostMessageFunction = () => {
  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)})();`;


export default class extends Component {
  onMessage = event => {
    const message = event.nativeEvent.data;
    const result = JSON.parse(message);

    if (!result.message) {
      return;
    }

    this.props.onChange({
       ...result
    });
  };

  render() {
    return (
          <WebView
            source={{
              uri: this.props.uri
            }}
            style={{ height: "100%" , width: "100%" }}
            onMessage={this.onMessage}
            injectedJavaScript={patchPostMessageJsCode}
          />
    );
  }
}

とりあえず解決!