Be patient and wait for the postMessage
method to be overridden by react-native's implementation. If not, you will be using the default postMessage
implementation. React Native replaces the global window.postMessage
with its own version of postMessage
that only takes one argument. Take a look at this code snippet:
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);
}
}
It's worth noting that there is a distinction between the injectJavaScript
and injectedJavaScript
properties.
injectedJavaScript
: allows you to inject JavaScript code to be executed within the WebView's context.
injectJavaScript
: lets you inject JavaScript code that is immediately executed in the WebView without returning a value.
If you want more information, check out this article - https://medium.com/capriza-engineering/communicating-between-react-native-and-the-webview-ac14b8b8b91a