Keine Beschreibung

index.android.js 7.2KB

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