question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

InjectJavascript or postMessage isn't work on Android (but iOS is works!)

See original GitHub issue

When I using Expo SDK35, all is well. but upgrading Expo SDK36, and I’m changing source related postMessage. It is working on iOS, but Android is abnormal.

The Flow is message is sent from the webView to the app, and the app that receives the message passes the token. In the webView that receives the token, the business logic is executed afterwards.

OS: macOS OS version: 10.14.6 react-native version: 0.61.5 (expo36) react-native-webview version: 7.4.3

I migrated to the URL below. https://github.com/react-native-community/react-native-webview/issues/809#issuecomment-547695298

function _postMessage() {
  const generateOnMessageFunction = (data) => 
     `(function() {
      window.dispatchEvent(new MessageEvent('message', {data: ${JSON.stringify(data)}}));
  })()`;

  webView.injectJavaScript(generateOnMessageFunction(message));
}

And This is part of source.

// app.js (RN)
<WebView
     ref={view => (this.webView = view)}
     source={{
       uri: this.state.endpoint
     }}
     onMessage={this._onMessage}
     useWebKit={true} 
     onNavigationStateChange={this._injectedToken}         // first of all, I injected a token
     startInLoadingState={true}
     renderLoading={this._activityIndicatorLoadingView}
/>

_onMessage = async event => {
    const receiveData = JSON.parse(event.nativeEvent.data);

    if (receiveData.action === "logout") {
      this.props._onLogoutToApp();
    } else if (receiveData.action === "token") {
      const token = await this.props._onTokenFromApp();
      _postMessage(this.webView, token);      // this is migrate guide source
    }
};
// web.js (WEB source)
...

function init(){
  var jsonData = {"action": "token", "type": "string"}; 
  _postMessage(JSON.stringify(jsonData), "*");
}

function _postMessage(message, target){
  (window["ReactNativeWebView"]||window).postMessage(message, target);
}

...

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13

github_iconTop GitHub Comments

6reactions
infazAcommented, Jan 6, 2020

Just use one parameter… It works on both iOS and Android.

Example :

window.ReactNativeWebView.postMessage("Hello React");

3reactions
aperomingocommented, Feb 24, 2020

This solution is for send data from WebView to React Native

SOLVED WITH setTimeout function on Web (JS) side using next function:

WEB:

setTimeout(() => {
    window.ReactNativeWebView &&
      window.ReactNativeWebView.postMessage(
        JSON.stringify({ type: "token", data: "kbadsfi74ty59y47934875v93ruhfekrt983457" })
      );
  }, 0);

REACT NATIVE:

<WebView
          ref={ref => (this.webview = ref)}
          source={{ uri: DASHBOARD_URL }}
          onNavigationStateChange={this.handleWebViewNavigationStateChange}
          onMessage={this.handleOnMessage}
          renderLoading={() => this.renderLoading()}
          startInLoadingState
          incognitotimes
        />

handleOnMessage(event) {
    const { type, data } = JSON.parse(event.nativeEvent.data)
    if (type === "token") {
      console.log('token', data)
    }
  }

In my opinion, this is horrible and the unique solution i have found.

Good luck.

Read more comments on GitHub >

github_iconTop Results From Across the Web

InjectJavascript or postMessage isn't work on Android (but iOS ...
It is working on iOS, but Android is abnormal. The Flow is message is sent from the webView to the app, and the...
Read more >
React Native WebView postMessage does not work
The React Native app successfully receives the post message sendt from the web app. But the web app does not receive messages sendt...
Read more >
Fixing React Native WebView's postMessage for iOS
In 2016, a GitHub user opened an issue on the React Native repository reporting the error, but nothing has been done to resolve...
Read more >
How to use WebView in React Native - Educative.io
Create a React Native project · Add dependencies · Link native dependencies · For iOS and macOS · For Android · Implementing a...
Read more >
WebView - React Native
Security Warning: Currently, onMessage and postMessage do not allow specifying an ... On iOS, when useWebKit=true , this prop will not work.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found