Keine Beschreibung

index.android.js 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. 'use strict';
  2. import React, { PureComponent } from 'react';
  3. import {
  4. findNodeHandle,
  5. requireNativeComponent,
  6. Animated,
  7. DeviceEventEmitter,
  8. Dimensions,
  9. StyleSheet,
  10. Platform,
  11. UIManager,
  12. View,
  13. ViewPropTypes,
  14. WebView
  15. } from 'react-native';
  16. import PropTypes from 'prop-types';
  17. import Immutable from 'immutable';
  18. import { getScript, onHeightUpdated, DomMutationObserveScript } from './common.js';
  19. const RCTAutoHeightWebView = requireNativeComponent('RCTAutoHeightWebView', AutoHeightWebView, {
  20. nativeOnly: {
  21. nativeOnly: {
  22. onLoadingStart: true,
  23. onLoadingError: true,
  24. onLoadingFinish: true,
  25. messagingEnabled: PropTypes.bool
  26. }
  27. }
  28. });
  29. export default class AutoHeightWebView extends PureComponent {
  30. static propTypes = {
  31. source: WebView.propTypes.source,
  32. onHeightUpdated: PropTypes.func,
  33. customScript: PropTypes.string,
  34. customStyle: PropTypes.string,
  35. enableAnimation: PropTypes.bool,
  36. // if set to false may cause some layout issues (width of container will be than width of screen)
  37. scalesPageToFit: PropTypes.bool,
  38. // only works on enable animation
  39. animationDuration: PropTypes.number,
  40. // offset of rn webView margin
  41. heightOffset: PropTypes.number,
  42. // baseUrl not work in android 4.3 or below version
  43. enableBaseUrl: PropTypes.bool,
  44. style: ViewPropTypes.style,
  45. // rn WebView callback
  46. onError: PropTypes.func,
  47. onLoad: PropTypes.func,
  48. onLoadStart: PropTypes.func,
  49. onLoadEnd: PropTypes.func,
  50. // works if set enableBaseUrl to true; add web/files... to android/app/src/assets/
  51. files: PropTypes.arrayOf(
  52. PropTypes.shape({
  53. href: PropTypes.string,
  54. type: PropTypes.string,
  55. rel: PropTypes.string
  56. })
  57. )
  58. };
  59. static defaultProps = {
  60. scalesPageToFit: true,
  61. enableBaseUrl: false,
  62. enableAnimation: true,
  63. animationDuration: 555,
  64. heightOffset: 20
  65. };
  66. constructor(props) {
  67. super(props);
  68. props.enableAnimation && (this.opacityAnimatedValue = new Animated.Value(0));
  69. this.state = {
  70. isChangingSource: false,
  71. height: 0,
  72. heightOffset: 0,
  73. script: getScript(props, BaseScript)
  74. };
  75. }
  76. componentWillMount() {
  77. IsBelowKitKat && DeviceEventEmitter.addListener('webViewBridgeMessage', this.listenWebViewBridgeMessage);
  78. }
  79. componentDidMount() {
  80. this.startInterval();
  81. }
  82. componentWillReceiveProps(nextProps) {
  83. // injectedJavaScript only works when webView reload (source changed)
  84. if (Immutable.is(Immutable.fromJS(this.props.source), Immutable.fromJS(nextProps.source))) {
  85. return;
  86. } else {
  87. this.setState(
  88. {
  89. isChangingSource: true,
  90. height: 0,
  91. heightOffset: 0
  92. },
  93. () => {
  94. this.startInterval();
  95. this.setState({ isChangingSource: false });
  96. }
  97. );
  98. }
  99. this.setState({ script: getScript(nextProps, BaseScript) });
  100. }
  101. componentWillUnmount() {
  102. this.stopInterval();
  103. IsBelowKitKat && DeviceEventEmitter.removeListener('webViewBridgeMessage', this.listenWebViewBridgeMessage);
  104. }
  105. // below kitkat
  106. listenWebViewBridgeMessage = body => this.onMessage(body.message);
  107. // below kitkat
  108. sendToWebView(message) {
  109. UIManager.dispatchViewManagerCommand(
  110. findNodeHandle(this.webView),
  111. UIManager.RCTAutoHeightWebView.Commands.sendToWebView,
  112. [String(message)]
  113. );
  114. }
  115. postMessage(data) {
  116. UIManager.dispatchViewManagerCommand(
  117. findNodeHandle(this.webView),
  118. UIManager.RCTAutoHeightWebView.Commands.postMessage,
  119. [String(data)]
  120. );
  121. }
  122. startInterval() {
  123. this.finishInterval = false;
  124. this.interval = setInterval(() => {
  125. if (!this.finishInterval) {
  126. IsBelowKitKat ? this.sendToWebView('getBodyHeight') : this.postMessage('getBodyHeight');
  127. }
  128. }, 205);
  129. }
  130. stopInterval() {
  131. this.finishInterval = true;
  132. clearInterval(this.interval);
  133. }
  134. onMessage = e => {
  135. const height = parseInt(IsBelowKitKat ? e.nativeEvent.message : e.nativeEvent.data);
  136. if (height) {
  137. const { enableAnimation, animationDuration, heightOffset } = this.props;
  138. if (enableAnimation) {
  139. this.opacityAnimatedValue.setValue(0);
  140. }
  141. this.stopInterval();
  142. this.setState(
  143. {
  144. heightOffset,
  145. height
  146. },
  147. () => {
  148. if (enableAnimation) {
  149. Animated.timing(this.opacityAnimatedValue, {
  150. toValue: 1,
  151. duration: animationDuration
  152. }).start(() => onHeightUpdated(height, this.props));
  153. } else {
  154. onHeightUpdated(height, this.props);
  155. }
  156. }
  157. );
  158. }
  159. };
  160. onLoadingStart = event => {
  161. const { onLoadStart } = this.props;
  162. onLoadStart && onLoadStart(event);
  163. };
  164. onLoadingError = event => {
  165. const { onError, onLoadEnd } = this.props;
  166. onError && onError(event);
  167. onLoadEnd && onLoadEnd(event);
  168. console.warn('Encountered an error loading page', event.nativeEvent);
  169. };
  170. onLoadingFinish = event => {
  171. const { onLoad, onLoadEnd } = this.props;
  172. onLoad && onLoad(event);
  173. onLoadEnd && onLoadEnd(event);
  174. };
  175. getWebView = webView => (this.webView = webView);
  176. stopLoading() {
  177. UIManager.dispatchViewManagerCommand(
  178. findNodeHandle(this.webView),
  179. UIManager.RCTAutoHeightWebView.Commands.stopLoading,
  180. null
  181. );
  182. }
  183. render() {
  184. const { height, script, isChangingSource, heightOffset } = this.state;
  185. const { scalesPageToFit, enableAnimation, source, customScript, style, enableBaseUrl } = this.props;
  186. let webViewSource = source;
  187. if (enableBaseUrl) {
  188. webViewSource = Object.assign({}, source, {
  189. baseUrl: 'file:///android_asset/web/'
  190. });
  191. }
  192. return (
  193. <Animated.View
  194. style={[
  195. Styles.container,
  196. {
  197. opacity: enableAnimation ? this.opacityAnimatedValue : 1,
  198. height: height + heightOffset
  199. },
  200. style
  201. ]}
  202. >
  203. {isChangingSource ? null : (
  204. <RCTAutoHeightWebView
  205. onLoadingStart={this.onLoadingStart}
  206. onLoadingFinish={this.onLoadingFinish}
  207. onLoadingError={this.onLoadingError}
  208. ref={this.getWebView}
  209. style={Styles.webView}
  210. javaScriptEnabled={true}
  211. injectedJavaScript={script + customScript}
  212. scalesPageToFit={scalesPageToFit}
  213. source={webViewSource}
  214. onMessage={this.onMessage}
  215. messagingEnabled={true}
  216. // below kitkat
  217. onChange={this.onMessage}
  218. />
  219. )}
  220. </Animated.View>
  221. );
  222. }
  223. }
  224. const ScreenWidth = Dimensions.get('window').width;
  225. const IsBelowKitKat = Platform.Version < 19;
  226. const Styles = StyleSheet.create({
  227. container: {
  228. width: ScreenWidth,
  229. backgroundColor: 'transparent'
  230. },
  231. webView: {
  232. flex: 1,
  233. backgroundColor: 'transparent'
  234. }
  235. });
  236. const BaseScript = IsBelowKitKat
  237. ? `
  238. ; (function () {
  239. AutoHeightWebView.onMessage = function (message) {
  240. AutoHeightWebView.send(String(document.body.offsetHeight));
  241. };
  242. ${DomMutationObserveScript}
  243. } ());
  244. `
  245. : `
  246. ; (function () {
  247. document.addEventListener('message', function (e) {
  248. window.postMessage(String(document.body.offsetHeight));
  249. });
  250. ${DomMutationObserveScript}
  251. } ());
  252. `;