Brak opisu

index.android.js 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. const RCTAutoHeightWebView = requireNativeComponent('RCTAutoHeightWebView', AutoHeightWebView, { nativeOnly: { messagingEnabled: PropTypes.bool } });
  19. export default class AutoHeightWebView extends PureComponent {
  20. static propTypes = {
  21. source: WebView.propTypes.source,
  22. onHeightUpdated: PropTypes.func,
  23. customScript: PropTypes.string,
  24. enableAnimation: PropTypes.bool,
  25. // if set to true may cause some layout issues (smaller font size)
  26. scalesPageToFit: PropTypes.bool,
  27. // only works on enable animation
  28. animationDuration: PropTypes.number,
  29. // offset of rn webview margin
  30. heightOffset: PropTypes.number,
  31. // baseUrl not work in android 4.3 or below version
  32. enableBaseUrl: PropTypes.bool,
  33. style: ViewPropTypes.style,
  34. // works if set enableBaseUrl to true; add web/files... to android/app/src/assets/
  35. files: PropTypes.arrayOf(PropTypes.shape({
  36. href: PropTypes.string,
  37. type: PropTypes.string,
  38. rel: PropTypes.string
  39. }))
  40. }
  41. static defaultProps = {
  42. scalesPageToFit: false,
  43. enableBaseUrl: false,
  44. enableAnimation: true,
  45. animationDuration: 555,
  46. heightOffset: 20
  47. }
  48. constructor(props) {
  49. super(props);
  50. this.onMessage = this.onMessage.bind(this);
  51. if (this.props.enableAnimation) {
  52. this.opacityAnimatedValue = new Animated.Value(0);
  53. }
  54. if (IsBelowKitKat) {
  55. this.listenWebViewBridgeMessage = this.listenWebViewBridgeMessage.bind(this);
  56. }
  57. const initialScript = props.files ? this.appendFilesToHead(props.files, BaseScript) : BaseScript;
  58. this.state = {
  59. isChangingSource: false,
  60. height: 0,
  61. heightOffset: 0,
  62. script: initialScript
  63. };
  64. }
  65. componentWillMount() {
  66. if (IsBelowKitKat) {
  67. DeviceEventEmitter.addListener("webViewBridgeMessage", this.listenWebViewBridgeMessage);
  68. }
  69. }
  70. componentDidMount() {
  71. this.startInterval();
  72. }
  73. componentWillReceiveProps(nextProps) {
  74. // injectedJavaScript only works when webview reload (source changed)
  75. if (Immutable.is(Immutable.fromJS(this.props.source), Immutable.fromJS(nextProps.source))) {
  76. return;
  77. }
  78. else {
  79. this.setState({
  80. isChangingSource: true,
  81. height: 0,
  82. heightOffset: 0
  83. }, () => {
  84. this.startInterval();
  85. this.setState({ isChangingSource: false });
  86. });
  87. }
  88. let currentScript = BaseScript;
  89. if (nextProps.files) {
  90. currentScript = this.appendFilesToHead(nextProps.files, BaseScript);
  91. }
  92. this.setState({ script: currentScript });
  93. }
  94. componentWillUnmount() {
  95. this.stopInterval();
  96. if (IsBelowKitKat) {
  97. DeviceEventEmitter.removeListener("webViewBridgeMessage", this.listenWebViewBridgeMessage);
  98. }
  99. }
  100. // below kitkat
  101. listenWebViewBridgeMessage(body) {
  102. this.onMessage(body.message);
  103. }
  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. onHeightUpdated(height) {
  132. if (this.props.onHeightUpdated) {
  133. this.props.onHeightUpdated(height);
  134. }
  135. }
  136. onMessage(e) {
  137. const height = parseInt(IsBelowKitKat ? e.nativeEvent.message : e.nativeEvent.data);
  138. if (height) {
  139. if (this.props.enableAnimation) {
  140. this.opacityAnimatedValue.setValue(0);
  141. }
  142. this.stopInterval();
  143. this.setState({
  144. heightOffset: this.props.heightOffset,
  145. height
  146. }, () => {
  147. if (this.props.enableAnimation) {
  148. Animated.timing(this.opacityAnimatedValue, {
  149. toValue: 1,
  150. duration: this.props.animationDuration
  151. }).start(() => this.onHeightUpdated(height));
  152. }
  153. else {
  154. this.onHeightUpdated(height);
  155. }
  156. });
  157. }
  158. }
  159. appendFilesToHead(files, script) {
  160. if (!files) {
  161. return script;
  162. }
  163. for (let file of files) {
  164. script =
  165. `
  166. var link = document.createElement('link');
  167. link.rel = '` + file.rel + `';
  168. link.type = '` + file.type + `';
  169. link.href = '` + file.href + `';
  170. document.head.appendChild(link);
  171. `+ script;
  172. }
  173. return script;
  174. }
  175. render() {
  176. const { height, script, isChangingSource, heightOffset } = this.state;
  177. const { scalesPageToFit, enableAnimation, source, customScript, style, enableBaseUrl } = this.props;
  178. let webViewSource = source;
  179. if (enableBaseUrl) {
  180. webViewSource = Object.assign({}, source, { baseUrl: 'file:///android_asset/web/' });
  181. }
  182. return (
  183. <Animated.View style={[Styles.container, {
  184. opacity: enableAnimation ? this.opacityAnimatedValue : 1,
  185. height: height + heightOffset,
  186. }, style]}>
  187. {
  188. isChangingSource ? null :
  189. <RCTAutoHeightWebView
  190. ref={webview => this.webview = webview}
  191. style={Styles.webView}
  192. javaScriptEnabled={true}
  193. injectedJavaScript={script + customScript}
  194. scalesPageToFit={scalesPageToFit}
  195. source={webViewSource}
  196. onMessage={this.onMessage}
  197. messagingEnabled={true}
  198. // below kitkat
  199. onChange={this.onMessage} />
  200. }
  201. </Animated.View>
  202. );
  203. }
  204. }
  205. const ScreenWidth = Dimensions.get('window').width;
  206. const IsBelowKitKat = Platform.Version < 19;
  207. const Styles = StyleSheet.create({
  208. container: {
  209. width: ScreenWidth,
  210. backgroundColor: 'transparent'
  211. },
  212. webView: {
  213. flex: 1,
  214. backgroundColor: 'transparent'
  215. }
  216. });
  217. const BaseScript =
  218. IsBelowKitKat ?
  219. `
  220. ; (function () {
  221. AutoHeightWebView.onMessage = function (message) {
  222. AutoHeightWebView.send(String(document.body.offsetHeight));
  223. };
  224. } ());
  225. ` :
  226. `
  227. ; (function () {
  228. document.addEventListener('message', function (e) {
  229. window.postMessage(String(document.body.offsetHeight));
  230. });
  231. } ());
  232. `;