mirror of
https://github.com/zhigang1992/react-native.git
synced 2026-05-10 17:33:36 +08:00
Implement a postMessage function and an onMessage event for webviews …
Summary: JS API very similar to web workers and node's child process. Work has been done by somebody else for the Android implementation over at #7020, so we'd need to have these in sync before anything gets merged. I've made a prop `messagingEnabled` to be more explicit about creating globals—it might be sufficient to just check for an onMessage handler though.  Closes https://github.com/facebook/react-native/pull/9762 Differential Revision: D4008260 fbshipit-source-id: 84b1afafbc0ab1edc3dfbf1a8fb870218e171a4c
This commit is contained in:
committed by
Facebook Github Bot
parent
6ea26c01de
commit
abb8ea3aea
@@ -217,6 +217,53 @@ class ScaledWebView extends React.Component {
|
||||
}
|
||||
}
|
||||
|
||||
class MessagingTest extends React.Component {
|
||||
webview = null
|
||||
|
||||
state = {
|
||||
messagesReceivedFromWebView: 0,
|
||||
message: '',
|
||||
}
|
||||
|
||||
onMessage = e => this.setState({
|
||||
messagesReceivedFromWebView: this.state.messagesReceivedFromWebView + 1,
|
||||
message: e.nativeEvent.data,
|
||||
})
|
||||
|
||||
postMessage = () => {
|
||||
if (this.webview) {
|
||||
this.webview.postMessage('"Hello" from React Native!');
|
||||
}
|
||||
}
|
||||
|
||||
render(): ReactElement<any> {
|
||||
const {messagesReceivedFromWebView, message} = this.state;
|
||||
|
||||
return (
|
||||
<View style={[styles.container, { height: 200 }]}>
|
||||
<View style={styles.container}>
|
||||
<Text>Messages received from web view: {messagesReceivedFromWebView}</Text>
|
||||
<Text>{message || '(No message)'}</Text>
|
||||
<View style={styles.buttons}>
|
||||
<Button text="Send Message to Web View" enabled onPress={this.postMessage} />
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.container}>
|
||||
<WebView
|
||||
ref={webview => { this.webview = webview; }}
|
||||
style={{
|
||||
backgroundColor: BGWASH,
|
||||
height: 100,
|
||||
}}
|
||||
source={require('./messagingtest.html')}
|
||||
onMessage={this.onMessage}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
var styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
@@ -391,5 +438,9 @@ exports.examples = [
|
||||
/>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
title: 'Mesaging Test',
|
||||
render(): ReactElement<any> { return <MessagingTest />; }
|
||||
}
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user