alinz / react-native-webview-bridge

React Native Webview with Javascript Bridge
MIT License
1.37k stars 491 forks source link

sendToBridge not working on Android #197

Open johnpaulmanoza opened 7 years ago

johnpaulmanoza commented 7 years ago

This code works fine in iOS but not in Android 6.0 Device.

onBridgeMessage = (obj) => {
    const { type, params } = JSON.parse(obj)
    console.log('did bridge message ', obj)
}

componentDidMount() {
    setTimeout(() => {
      //console.log('now ready')
      this.refs.webviewBridge.sendToBridge("{type: 'READY'}")
    }, 2000);
}

render() {
    return (
      <View style={{flex: 1}}>
        <WebViewBridge
          pagingEnabled={true}
          javaScriptEnabled={true}
          ref='webviewBridge'
          onBridgeMessage={this.onBridgeMessage.bind(this)}
          style={{marginTop: 64}}
          source={{ html: this.state.html }}
        />
      </View>
    );
  }
MatthewAwesome commented 7 years ago

I was having the same issue. Seems to be an issue with Android and ES6 syntax that is specific to the WebView-Bridge extension. It worked once I changed reverted my code to ES5. Hope this quick fix works for you too! Stay awesome!

facuescobar commented 7 years ago

@johnpaulmanoza have you fixed this? I am having the same issue.

@MatthewAwesome your answer doesn't help at all. If you are not going to investigate specific cases, don't waste time posting generic answers.

facuescobar commented 7 years ago

My solution to make it work:

I am injecting some JS code to read cookies in WebViewBridge , and the injected code wasn't running. The issue was that Android doesn't allow commented code or 'spaces'.

So I removed unnecessary code from my injectedJS and started to work.

_injectScript = `function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
var transactionToken;
(function () {
if (WebViewBridge){
WebViewBridge.onMessage = function () {
WebViewBridge.send(document.cookie);
};
}
}());`;
baifengming1986 commented 6 years ago

@facuescobar I have the same problem,I use sendToBridge method send JSON string,I use JSON.parse to parse the JSON string in html,but it not working. how can i resolve this problem?