Files
react-native-webview/example/examples/Messaging.tsx
T
Tero Paananen b930e25a8f feat(windows): JS-WebView messaging bridge & multiple WebViews fixes (#1617)
* Manage to build webview using Visual Studio

* WebView in content of UserControl

* Destructor not needed

* Example app tested

* Add messagingEnabled prop

* WebViewBridge

* Message posting

* Store bridge as instance variable

* Use bridge if messagingEnabled

* Free event delegate

* PostMessage api uses string message

* script.notify() usage removed

* Debug log removed

* Bridge reference added

* Base for web allowed object implemented c++/winrt

* Bribge works

* "Microsoft.Windows.CppWinRT" version="2.0.200729.8"

* Update bridge implementation

* version changes

* Reference fix

* WebView prj builds

* yarn lock update

* Platfrom version update

* NuGet package reference updated

* Messaging test added into example app

* Typo fix

* try_as() to as() calls

* WebView.PostMessage() not supported anymore, use injectJavaScript

* Fix WebView.postMessage to work using injectJavascript

* Eval postMessage fix

* postMessage via injectJavascript

* Example fixed to handle postMessage call
2020-10-26 14:01:40 +01:00

64 lines
1.6 KiB
TypeScript

import React, {Component} from 'react';
import {View, Alert} from 'react-native';
import WebView from 'react-native-webview';
const HTML = `<!DOCTYPE html>\n
<html>
<head>
<title>Messaging</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=320, user-scalable=no">
<style type="text/css">
body {
margin: 0;
padding: 0;
font: 62.5% arial, sans-serif;
background: #ccc;
}
</style>
</head>
<body>
<button onclick="sendPostMessage()">Send post message from JS to WebView</button>
<p id="demo"></p>
<script>
function sendPostMessage() {
window.ReactNativeWebView.postMessage('Message from JS');
}
window.addEventListener('message',function(event){
console.log("Message received from RN: ",event.data)
},false);
</script>
</body>
</html>`;
type Props = {};
type State = {};
export default class Messaging extends Component<Props, State> {
state = {};
constructor(props) {
super(props);
this.webView = React.createRef();
}
render() {
return (
<View style={{height: 120}}>
<WebView
ref={this.webView}
source={{html: HTML}}
onLoadEnd={()=>{this.webView.current.postMessage('Hello from RN');}}
automaticallyAdjustContentInsets={false}
onMessage={(e: {nativeEvent: {data?: string}}) => {
Alert.alert('Message received from JS: ', e.nativeEvent.data);
}}
/>
</View>
);
}
}