No Description

WebView.macos.tsx 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import React from 'react';
  2. import {
  3. UIManager as NotTypedUIManager,
  4. View,
  5. requireNativeComponent,
  6. NativeModules,
  7. Image,
  8. findNodeHandle,
  9. ImageSourcePropType,
  10. } from 'react-native';
  11. import invariant from 'invariant';
  12. import {
  13. defaultOriginWhitelist,
  14. createOnShouldStartLoadWithRequest,
  15. defaultRenderError,
  16. defaultRenderLoading,
  17. } from './WebViewShared';
  18. import {
  19. WebViewErrorEvent,
  20. WebViewHttpErrorEvent,
  21. WebViewMessageEvent,
  22. WebViewNavigationEvent,
  23. WebViewProgressEvent,
  24. WebViewTerminatedEvent,
  25. MacOSWebViewProps,
  26. NativeWebViewMacOS,
  27. ViewManager,
  28. State,
  29. RNCWebViewUIManagerMacOS,
  30. } from './WebViewTypes';
  31. import styles from './WebView.styles';
  32. const UIManager = NotTypedUIManager as RNCWebViewUIManagerMacOS;
  33. const { resolveAssetSource } = Image;
  34. const RNCWebViewManager = NativeModules.RNCWebViewManager as ViewManager;
  35. const RNCWebView: typeof NativeWebViewMacOS = requireNativeComponent(
  36. 'RNCWebView',
  37. );
  38. class WebView extends React.Component<MacOSWebViewProps, State> {
  39. static defaultProps = {
  40. javaScriptEnabled: true,
  41. cacheEnabled: true,
  42. originWhitelist: defaultOriginWhitelist,
  43. useSharedProcessPool: true,
  44. };
  45. static isFileUploadSupported = async () => {
  46. // no native implementation for macOS, depends only on permissions
  47. return true;
  48. };
  49. state: State = {
  50. viewState: this.props.startInLoadingState ? 'LOADING' : 'IDLE',
  51. lastErrorEvent: null,
  52. };
  53. webViewRef = React.createRef<NativeWebViewMacOS>();
  54. // eslint-disable-next-line react/sort-comp
  55. getCommands = () => UIManager.getViewManagerConfig('RNCWebView').Commands;
  56. /**
  57. * Go forward one page in the web view's history.
  58. */
  59. goForward = () => {
  60. UIManager.dispatchViewManagerCommand(
  61. this.getWebViewHandle(),
  62. this.getCommands().goForward,
  63. undefined,
  64. );
  65. };
  66. /**
  67. * Go back one page in the web view's history.
  68. */
  69. goBack = () => {
  70. UIManager.dispatchViewManagerCommand(
  71. this.getWebViewHandle(),
  72. this.getCommands().goBack,
  73. undefined,
  74. );
  75. };
  76. /**
  77. * Reloads the current page.
  78. */
  79. reload = () => {
  80. this.setState({ viewState: 'LOADING' });
  81. UIManager.dispatchViewManagerCommand(
  82. this.getWebViewHandle(),
  83. this.getCommands().reload,
  84. undefined,
  85. );
  86. };
  87. /**
  88. * Stop loading the current page.
  89. */
  90. stopLoading = () => {
  91. UIManager.dispatchViewManagerCommand(
  92. this.getWebViewHandle(),
  93. this.getCommands().stopLoading,
  94. undefined,
  95. );
  96. };
  97. /**
  98. * Request focus on WebView rendered page.
  99. */
  100. requestFocus = () => {
  101. UIManager.dispatchViewManagerCommand(
  102. this.getWebViewHandle(),
  103. this.getCommands().requestFocus,
  104. undefined,
  105. );
  106. };
  107. /**
  108. * Posts a message to the web view, which will emit a `message` event.
  109. * Accepts one argument, `data`, which must be a string.
  110. *
  111. * In your webview, you'll need to something like the following.
  112. *
  113. * ```js
  114. * document.addEventListener('message', e => { document.title = e.data; });
  115. * ```
  116. */
  117. postMessage = (data: string) => {
  118. UIManager.dispatchViewManagerCommand(
  119. this.getWebViewHandle(),
  120. this.getCommands().postMessage,
  121. [String(data)],
  122. );
  123. };
  124. /**
  125. * Injects a javascript string into the referenced WebView. Deliberately does not
  126. * return a response because using eval() to return a response breaks this method
  127. * on pages with a Content Security Policy that disallows eval(). If you need that
  128. * functionality, look into postMessage/onMessage.
  129. */
  130. injectJavaScript = (data: string) => {
  131. UIManager.dispatchViewManagerCommand(
  132. this.getWebViewHandle(),
  133. this.getCommands().injectJavaScript,
  134. [data],
  135. );
  136. };
  137. /**
  138. * We return an event with a bunch of fields including:
  139. * url, title, loading, canGoBack, canGoForward
  140. */
  141. updateNavigationState = (event: WebViewNavigationEvent) => {
  142. if (this.props.onNavigationStateChange) {
  143. this.props.onNavigationStateChange(event.nativeEvent);
  144. }
  145. };
  146. /**
  147. * Returns the native `WebView` node.
  148. */
  149. getWebViewHandle = () => {
  150. const nodeHandle = findNodeHandle(this.webViewRef.current);
  151. invariant(nodeHandle != null, 'nodeHandle expected to be non-null');
  152. return nodeHandle as number;
  153. };
  154. onLoadingStart = (event: WebViewNavigationEvent) => {
  155. const { onLoadStart } = this.props;
  156. if (onLoadStart) {
  157. onLoadStart(event);
  158. }
  159. this.updateNavigationState(event);
  160. };
  161. onLoadingError = (event: WebViewErrorEvent) => {
  162. event.persist(); // persist this event because we need to store it
  163. const { onError, onLoadEnd } = this.props;
  164. if (onLoadEnd) {
  165. onLoadEnd(event);
  166. }
  167. if (onError) {
  168. onError(event);
  169. }
  170. console.warn('Encountered an error loading page', event.nativeEvent);
  171. this.setState({
  172. lastErrorEvent: event.nativeEvent,
  173. viewState: 'ERROR',
  174. });
  175. };
  176. onHttpError = (event: WebViewHttpErrorEvent) => {
  177. const { onHttpError } = this.props;
  178. if (onHttpError) {
  179. onHttpError(event);
  180. }
  181. }
  182. onLoadingFinish = (event: WebViewNavigationEvent) => {
  183. const { onLoad, onLoadEnd } = this.props;
  184. if (onLoad) {
  185. onLoad(event);
  186. }
  187. if (onLoadEnd) {
  188. onLoadEnd(event);
  189. }
  190. this.setState({
  191. viewState: 'IDLE',
  192. });
  193. this.updateNavigationState(event);
  194. };
  195. onMessage = (event: WebViewMessageEvent) => {
  196. const { onMessage } = this.props;
  197. if (onMessage) {
  198. onMessage(event);
  199. }
  200. };
  201. onLoadingProgress = (event: WebViewProgressEvent) => {
  202. const { onLoadProgress } = this.props;
  203. if (onLoadProgress) {
  204. onLoadProgress(event);
  205. }
  206. };
  207. onShouldStartLoadWithRequestCallback = (
  208. shouldStart: boolean,
  209. _url: string,
  210. lockIdentifier: number,
  211. ) => {
  212. const viewManager
  213. = (this.props.nativeConfig && this.props.nativeConfig.viewManager)
  214. || RNCWebViewManager;
  215. viewManager.startLoadWithResult(!!shouldStart, lockIdentifier);
  216. };
  217. onContentProcessDidTerminate = (event: WebViewTerminatedEvent) => {
  218. const { onContentProcessDidTerminate } = this.props;
  219. if (onContentProcessDidTerminate) {
  220. onContentProcessDidTerminate(event);
  221. }
  222. };
  223. componentDidUpdate(prevProps: MacOSWebViewProps) {
  224. this.showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
  225. this.showRedboxOnPropChanges(prevProps, 'incognito');
  226. this.showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
  227. }
  228. showRedboxOnPropChanges(
  229. prevProps: MacOSWebViewProps,
  230. propName: keyof MacOSWebViewProps,
  231. ) {
  232. if (this.props[propName] !== prevProps[propName]) {
  233. console.error(
  234. `Changes to property ${propName} do nothing after the initial render.`,
  235. );
  236. }
  237. }
  238. render() {
  239. const {
  240. nativeConfig = {},
  241. onMessage,
  242. onShouldStartLoadWithRequest: onShouldStartLoadWithRequestProp,
  243. originWhitelist,
  244. renderError,
  245. renderLoading,
  246. style,
  247. containerStyle,
  248. ...otherProps
  249. } = this.props;
  250. let otherView = null;
  251. if (this.state.viewState === 'LOADING') {
  252. otherView = (renderLoading || defaultRenderLoading)();
  253. } else if (this.state.viewState === 'ERROR') {
  254. const errorEvent = this.state.lastErrorEvent;
  255. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  256. otherView = (renderError || defaultRenderError)(
  257. errorEvent.domain,
  258. errorEvent.code,
  259. errorEvent.description,
  260. );
  261. } else if (this.state.viewState !== 'IDLE') {
  262. console.error(
  263. `RNCWebView invalid state encountered: ${this.state.viewState}`,
  264. );
  265. }
  266. const webViewStyles = [styles.container, styles.webView, style];
  267. const webViewContainerStyle = [styles.container, containerStyle];
  268. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  269. this.onShouldStartLoadWithRequestCallback,
  270. // casting cause it's in the default props
  271. originWhitelist as readonly string[],
  272. onShouldStartLoadWithRequestProp,
  273. );
  274. const NativeWebView
  275. = (nativeConfig.component as typeof NativeWebViewMacOS | undefined)
  276. || RNCWebView;
  277. const webView = (
  278. <NativeWebView
  279. key="webViewKey"
  280. {...otherProps}
  281. messagingEnabled={typeof onMessage === 'function'}
  282. onLoadingError={this.onLoadingError}
  283. onLoadingFinish={this.onLoadingFinish}
  284. onLoadingProgress={this.onLoadingProgress}
  285. onLoadingStart={this.onLoadingStart}
  286. onHttpError={this.onHttpError}
  287. onMessage={this.onMessage}
  288. onScroll={this.props.onScroll}
  289. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  290. onContentProcessDidTerminate={this.onContentProcessDidTerminate}
  291. ref={this.webViewRef}
  292. // TODO: find a better way to type this.
  293. source={resolveAssetSource(this.props.source as ImageSourcePropType)}
  294. style={webViewStyles}
  295. {...nativeConfig.props}
  296. />
  297. );
  298. return (
  299. <View style={webViewContainerStyle}>
  300. {webView}
  301. {otherView}
  302. </View>
  303. );
  304. }
  305. }
  306. export default WebView;