Send WebView a Message with React Native

#React Native

whck6

最近在玩 React Native 遇到的一個問題。假如想讓 WebView 與 React Native 溝通的話可以用 onMessage 這個介面。

假如原本的網頁內容你不確定怎麼寫的,可能會遇到 Setting onMessage on a WebView overrides existing values of window.postMessage.

可能的處理辦法

const patchPostMessageFunction = () => {
  const originalPostMessage = window.postMessage;

  const patchedPostMessage = (message, targetOrigin, transfer) => {
    originalPostMessage(message, targetOrigin, transfer);
  };

  patchedPostMessage.toString = () =>
    String(Object.hasOwnProperty).replace("hasOwnProperty", "postMessage");

  window.postMessage = patchedPostMessage;
};

const patchPostMessageJsCode = `(${String(patchPostMessageFunction)})();`;