Keine Beschreibung

index.android.js 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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, {
  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. this.onMessage = this.onMessage.bind(this);
  68. if (this.props.enableAnimation) {
  69. this.opacityAnimatedValue = new Animated.Value(0);
  70. }
  71. if (IsBelowKitKat) {
  72. this.listenWebViewBridgeMessage = this.listenWebViewBridgeMessage.bind(this);
  73. }
  74. let initialScript = props.files ? this.appendFilesToHead(props.files, BaseScript) : BaseScript;
  75. initialScript = props.customStyle ? this.appendStylesToHead(props.customStyle, initialScript) : initialScript;
  76. this.state = {
  77. isChangingSource: false,
  78. height: 0,
  79. heightOffset: 0,
  80. script: initialScript
  81. };
  82. }
  83. componentWillMount() {
  84. if (IsBelowKitKat) {
  85. DeviceEventEmitter.addListener('webViewBridgeMessage', this.listenWebViewBridgeMessage);
  86. }
  87. }
  88. componentDidMount() {
  89. this.startInterval();
  90. }
  91. componentWillReceiveProps(nextProps) {
  92. // injectedJavaScript only works when webView reload (source changed)
  93. if (Immutable.is(Immutable.fromJS(this.props.source), Immutable.fromJS(nextProps.source))) {
  94. return;
  95. } else {
  96. this.setState(
  97. {
  98. isChangingSource: true,
  99. height: 0,
  100. heightOffset: 0
  101. },
  102. () => {
  103. this.startInterval();
  104. this.setState({ isChangingSource: false });
  105. }
  106. );
  107. }
  108. let currentScript = BaseScript;
  109. if (nextProps.files) {
  110. currentScript = this.appendFilesToHead(nextProps.files, BaseScript);
  111. }
  112. currentScript = nextProps.customStyle
  113. ? this.appendStylesToHead(nextProps.customStyle, currentScript)
  114. : currentScript;
  115. this.setState({ script: currentScript });
  116. }
  117. componentWillUnmount() {
  118. this.stopInterval();
  119. if (IsBelowKitKat) {
  120. DeviceEventEmitter.removeListener('webViewBridgeMessage', this.listenWebViewBridgeMessage);
  121. }
  122. }
  123. // below kitkat
  124. listenWebViewBridgeMessage(body) {
  125. this.onMessage(body.message);
  126. }
  127. // below kitkat
  128. sendToWebView(message) {
  129. UIManager.dispatchViewManagerCommand(
  130. findNodeHandle(this.webView),
  131. UIManager.RCTAutoHeightWebView.Commands.sendToWebView,
  132. [String(message)]
  133. );
  134. }
  135. postMessage(data) {
  136. UIManager.dispatchViewManagerCommand(
  137. findNodeHandle(this.webView),
  138. UIManager.RCTAutoHeightWebView.Commands.postMessage,
  139. [String(data)]
  140. );
  141. }
  142. startInterval() {
  143. this.finishInterval = false;
  144. this.interval = setInterval(() => {
  145. if (!this.finishInterval) {
  146. IsBelowKitKat ? this.sendToWebView('getBodyHeight') : this.postMessage('getBodyHeight');
  147. }
  148. }, 205);
  149. }
  150. stopInterval() {
  151. this.finishInterval = true;
  152. clearInterval(this.interval);
  153. }
  154. onHeightUpdated(height) {
  155. if (this.props.onHeightUpdated) {
  156. this.props.onHeightUpdated(height);
  157. }
  158. }
  159. onMessage(e) {
  160. const height = parseInt(IsBelowKitKat ? e.nativeEvent.message : e.nativeEvent.data);
  161. if (height) {
  162. if (this.props.enableAnimation) {
  163. this.opacityAnimatedValue.setValue(0);
  164. }
  165. this.stopInterval();
  166. this.setState(
  167. {
  168. heightOffset: this.props.heightOffset,
  169. height
  170. },
  171. () => {
  172. if (this.props.enableAnimation) {
  173. Animated.timing(this.opacityAnimatedValue, {
  174. toValue: 1,
  175. duration: this.props.animationDuration
  176. }).start(() => this.onHeightUpdated(height));
  177. } else {
  178. this.onHeightUpdated(height);
  179. }
  180. }
  181. );
  182. }
  183. }
  184. appendFilesToHead(files, script) {
  185. if (!files) {
  186. return script;
  187. }
  188. return files.reduceRight(
  189. (file, combinedScript) => `
  190. var link = document.createElement('link');
  191. link.rel = '${file.rel}';
  192. link.type = '${file.type}';
  193. link.href = '${file.href}';
  194. document.head.appendChild(link);
  195. ${combinedScript}
  196. `,
  197. script
  198. );
  199. }
  200. appendStylesToHead(styles, script) {
  201. if (!styles) {
  202. return script;
  203. }
  204. // Escape any single quotes or newlines in the CSS with .replace()
  205. const escaped = styles.replace(/\'/g, "\\'").replace(/\n/g, '\\n');
  206. return `
  207. var styleElement = document.createElement('style');
  208. var styleText = document.createTextNode('${escaped}');
  209. styleElement.appendChild(styleText);
  210. document.head.appendChild(styleElement);
  211. ${script}
  212. `;
  213. }
  214. onLoadingStart = event => {
  215. var onLoadStart = this.props.onLoadStart;
  216. onLoadStart && onLoadStart(event);
  217. };
  218. onLoadingError = event => {
  219. var { onError, onLoadEnd } = this.props;
  220. onError && onError(event);
  221. onLoadEnd && onLoadEnd(event);
  222. console.warn('Encountered an error loading page', event.nativeEvent);
  223. };
  224. onLoadingFinish = event => {
  225. var { onLoad, onLoadEnd } = this.props;
  226. onLoad && onLoad(event);
  227. onLoadEnd && onLoadEnd(event);
  228. };
  229. getWebView = webView => (this.webView = webView);
  230. stopLoading() {
  231. UIManager.dispatchViewManagerCommand(
  232. findNodeHandle(this.webView),
  233. UIManager.RCTAutoHeightWebView.Commands.stopLoading,
  234. null
  235. );
  236. }
  237. render() {
  238. const { height, script, isChangingSource, heightOffset } = this.state;
  239. const { scalesPageToFit, enableAnimation, source, customScript, style, enableBaseUrl } = this.props;
  240. let webViewSource = source;
  241. if (enableBaseUrl) {
  242. webViewSource = Object.assign({}, source, {
  243. baseUrl: 'file:///android_asset/web/'
  244. });
  245. }
  246. return (
  247. <Animated.View
  248. style={[
  249. Styles.container,
  250. {
  251. opacity: enableAnimation ? this.opacityAnimatedValue : 1,
  252. height: height + heightOffset
  253. },
  254. style
  255. ]}
  256. >
  257. {isChangingSource ? null : (
  258. <RCTAutoHeightWebView
  259. onLoadingStart={this.onLoadingStart}
  260. onLoadingFinish={this.onLoadingFinish}
  261. onLoadingError={this.onLoadingError}
  262. ref={this.getWebView}
  263. style={Styles.webView}
  264. javaScriptEnabled={true}
  265. injectedJavaScript={script + customScript}
  266. scalesPageToFit={scalesPageToFit}
  267. source={webViewSource}
  268. onMessage={this.onMessage}
  269. messagingEnabled={true}
  270. // below kitkat
  271. onChange={this.onMessage}
  272. />
  273. )}
  274. </Animated.View>
  275. );
  276. }
  277. }
  278. const ScreenWidth = Dimensions.get('window').width;
  279. const IsBelowKitKat = Platform.Version < 19;
  280. const Styles = StyleSheet.create({
  281. container: {
  282. width: ScreenWidth,
  283. backgroundColor: 'transparent'
  284. },
  285. webView: {
  286. flex: 1,
  287. backgroundColor: 'transparent'
  288. }
  289. });
  290. const BaseScript = IsBelowKitKat
  291. ? `
  292. ; (function () {
  293. AutoHeightWebView.onMessage = function (message) {
  294. AutoHeightWebView.send(String(document.body.offsetHeight));
  295. };
  296. MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  297. var observer = new MutationObserver(function() {
  298. AutoHeightWebView.send(String(document.body.offsetHeight));
  299. });
  300. observer.observe(document, {
  301. subtree: true,
  302. attributes: true
  303. });
  304. } ());
  305. `
  306. : `
  307. ; (function () {
  308. document.addEventListener('message', function (e) {
  309. window.postMessage(String(document.body.offsetHeight));
  310. });
  311. MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  312. var observer = new MutationObserver(function() {
  313. window.postMessage(String(document.body.offsetHeight));
  314. });
  315. observer.observe(document, {
  316. subtree: true,
  317. attributes: true
  318. });
  319. } ());
  320. `;