Skip to content

Instantly share code, notes, and snippets.

@woshi82
Created November 26, 2017 11:02
Show Gist options
  • Save woshi82/9c03ad6c836ecd172b701a34cd559b48 to your computer and use it in GitHub Desktop.
Save woshi82/9c03ad6c836ecd172b701a34cd559b48 to your computer and use it in GitHub Desktop.
// react-native webview onMessage and postMessage BUG https://github.com/facebook/react-native/issues/10865
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
WebView,
ScrollView,
View
} from 'react-native';
let thisWebView=null;
export default class testrn extends Component {
constructor(e){
super(e);
}
handleNavigationChange(){
let a= new Date().getTime();
const script = 'window.postMessage("'+a+'")'; // eslint-disable-line quotes
thisWebView && thisWebView.injectJavaScript(script);
// alert("df")
}
_onMessage (e) {
alert(e.nativeEvent.data);
}
render() {
const patchPostMessageFunction = function() {
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
};
const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';
return (
<ScrollView style={{flex:1}}>
<View style={{ height: 2232,}}>
<WebView
ref={webview => { thisWebView = webview; }}
injectedJavaScript={patchPostMessageJsCode}
source={{uri: "http://68xg.com?"}}
onLoadEnd={this.handleNavigationChange}
onMessage={this._onMessage}
/>
</View>
<Text>文字文字</Text>
</ScrollView>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment