lancey
lancey

Reputation: 377

onMessage not wot working in react native

I am trying to get the content of a url by injecting a post message and listening for it onMessage but it is not working.

render(){
const getHtmlJS = "window.postMessage(document.getElementsByTagName('head').innerHTML)";
return (
<View>
    <WebView
      source={{uri: this.state.url}}
      style={{flex: 1}}
      onMessage={(string) => this._onMessage(string)}
      injectedJavaScript={getHtmlJS}
    />
  </View>
)}

Any idea why this may not work?

Upvotes: 1

Views: 3000

Answers (1)

Noitidart
Noitidart

Reputation: 37238

Wait for postMessage to get overriden by react-native implementation. Otherwise you are using default postMessage implementation. What RN does, is replaces the window.postMessage with it's own postMessage which takes only one argument. See here:

const SCRIPT = `
    function init() {
        postMessage('LOADED:');
    }
    function whenRNPostMessageReady(cb) {
        if (postMessage.length === 1) cb();
        else setTimeout(function() { whenRNPostMessageReady(cb) }, 1000);
    }
    if (document.readyState === 'complete') {
        whenRNPostMessageReady(init);
    } else {
        window.addEventListener('load', function() {
            whenRNPostMessageReady(init);
        }, false);
    }
`

class ScreenWidget extends Component {
    render() {
        return (
            <View style={styles.main}>
                <WebView source={{ uri:'https://www.duckduckgo.com' }} injectedJavaScript={SCRIPT} onMessage={this.handleMessage} />
            </View>
        )
    }

    handleMessage = ({nativeEvent:{ data }}) => {
        console.log('got message, data:', data);
    }
}

On a side note, there is difference between injectJavaScript and injectedJavaScript property.

injectedJavaScript: lets you inject JavaScript code to be executed within the context of the WebView.

injectJavaScript: lets you inject JavaScript code that is executed immediately on the WebView, with no return value.

You can read more about it here - https://medium.com/capriza-engineering/communicating-between-react-native-and-the-webview-ac14b8b8b91a

Upvotes: 1

Related Questions