我不太清楚如何实现 onMessage
和 postMessage
,我可以获取整个网页,但只能从 react native 端获取。
我的意思是,我将使用 injectedJavaScript
var markup = document.documentElement.innerHTML
window.postMessage(markup)
我将使用 onMessage
收到结果。到目前为止我不能这样做是可能的原因吗
最佳答案
是的,您可以做到这一点,您所要做的就是使用您的网页中的 window.postMessage("message")
,该网页将在 WebView
中加载您可以在 onMessage
属性中看到该消息。
示例:
class Test extends React.Component{
constructor(props){
super(props);
this.state:{
html:''
}
}
componentWillMount(){
this.setState({
html : `<html>
<head>
<script>
window.postMessage("Messga from webView")
</script>
</head>
<body><h1>Hello from webView</h1></body>
</html>`
})
}
render(){
return (
<View style={{flex: 1}}>
<WebView
ref={(reff) => {
this.webView = reff;
}}
source={{html: this.state.html}}
style={[styles.flex1, styles.padding5]}
onMessage={(event)=>{
let message = event.nativeEvent.data;
/* event.nativeEvent.data must be string, i.e. window.postMessage
should send only string.
* */
}}
onNavigationStateChange={(evt)=>{}}
onError={(e) => {
console.warn('error occured', e)
}}/>
</View>
)
}
}
我刚刚添加了一个示例 html 并在 WebView
中呈现它,您可以在要在 WebView
中加载的页面中执行相同的操作。
或者另一种解决方案是:
您可以使用 WebView
的 injectedJavaScript
或 injectJavaScript
属性,如 here 所述.
关于react-native - React Native WebView onMessage 和 postMessage 以获取所有网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47040733/