Skip to content

Migrating from react-native-webview

Each react-native-webview prop's counterpart here, and the defaults and behavior that differ. The requirements are in the README.

Most props are platform settings by the same name: bounces is ios={{ scrollView: { bounces: false } }}, and textZoom is android={{ settings: { textZoom: 120 } }}. An enum string becomes a constant: cacheMode: 'LOAD_NO_CACHE' is AndroidConstants.WebSettings.LOAD_NO_CACHE. For a prop no table here lists, find its key in Use a platform API.

Defaults that differ

react-native-webview Here To get the old behavior
Android overscroll Always The platform's android.webView.overScrollMode: 0
iOS inline video Off On ios.configuration.allowsInlineMediaPlayback: false
iOS AirPlay Off On ios.configuration.allowsAirPlayForMediaPlayback: false
iOS data detectors (dataDetectorTypes) Phone numbers None ios.configuration.dataDetectorTypes: IOSConstants.DataDetectorTypes.phoneNumber
iOS content insets never, indicators not adjusted automatic, indicators adjusted Two ios.scrollView keys, below
iOS debugging (webviewDebuggingEnabled) Off On in __DEV__ ios.webView.inspectable: false
Android back-forward cache Off On, with Android System WebView 146 and newer android.settings.backForwardCacheEnabled: false

The same settings in one object, debugging and the back-forward cache left on:

import { IOSConstants, WebView, type WebViewProps } from 'react-native-minimal-webview';

export const rnwDefaults = {
  ios: {
    configuration: {
      allowsInlineMediaPlayback: false,
      allowsAirPlayForMediaPlayback: false,
      dataDetectorTypes: IOSConstants.DataDetectorTypes.phoneNumber,
    },
    scrollView: {
      contentInsetAdjustmentBehavior: IOSConstants.ContentInsetAdjustmentBehavior.never,
      automaticallyAdjustsScrollIndicatorInsets: false,
    },
  },
  android: {
    webView: { overScrollMode: 0 }, // 0: View.OVER_SCROLL_ALWAYS
  },
} satisfies Pick<WebViewProps, 'ios' | 'android'>;

export function Browser() {
  return (
    <WebView
      source={{ uri: 'https://example.com' }}
      ios={rnwDefaults.ios}
      android={rnwDefaults.android}
      style={{ flex: 1 }}
    />
  );
}

To add your own keys, merge each root: ios={{ ...rnwDefaults.ios, scrollView: { ...rnwDefaults.ios.scrollView, bounces: false } }}.

Behavior that differs

react-native-webview Here To get the old behavior
Android fullscreen video (allowsFullscreenVideo) Off On (onFullscreenChange) A native hook that takes onShowCustomView
iOS universal links Open the app that claims them Load in place An external rule for the host
Downloads Android: saved to Downloads Open externally, or onDownload saves them downloadManager (Android)
Renderer crash Reported The core reloads (onProcessGone) Remove your reload(), and offer a retry while recovered is false
Messaging Every page; on Android every frame allowedOrigins, main frame An iframe's: a native hook
Injected script Document end, every origin Document start, its origins addEventListener('DOMContentLoaded', …); origins: ['*']
Failed load An error view over the page iOS keeps the old page, Android shows its own The error screen
Android file input Offers the camera, and with capture opens it directly The system chooser, which ignores capture onFileRequest
Android camera and microphone, and location with geolocationEnabled Granted to every page, after asking the OS Denied onPermissionRequest
A link to another scheme (tel:, myapp:) Opens externally Only from the main frame, after a user gesture An external rule for the scheme
New window (target=_blank, window.open) In place; on Android in the system browser In place, when a rule allows it (newWindow) { newWindow: true, action: 'external' }
Android System WebView older than 101 Messaging and injected scripts work Neither does (versions)

Remove the LSApplicationQueriesSchemes (iOS) and <queries> (Android) entries you added for the schemes a page opens (onOpenExternal), unless your own code calls Linking.canOpenURL for them.

Props that became something else

react-native-webview Here
onShouldStartLoadWithRequest, originWhitelist, onOpenWindow, setSupportMultipleWindows navigationRules (below)
injectedJavaScript, injectedJavaScriptBeforeContentLoaded, injectedJavaScriptObject injectedScripts
…ForMainFrameOnly: false allFrames: true on the script
injectJavaScript(code) evaluate(expression) (below)
injectJavaScript('window.location = …'), a new source to navigate load(url)
onMessage, postMessage, window.ReactNativeWebView The bridge (below)
onLoad onLoadEnd, with state.outcome === 'finished'
onLoadProgress progress in useWebViewState
onError, onHttpError onError, whose kind is 'network', 'ssl' or 'http'
onContentProcessDidTerminate, onRenderProcessGone onProcessGone, whose cause is 'crash', 'memory' or, on iOS, 'unknown'
renderLoading, renderError, startInLoadingState Your own views, shown on every load
onContentSizeChange An injected script, as for the scroll position
ignoreSilentHardwareSwitch An injected script that sets navigator.audioSession.type = 'playback'
source={require('./page.html')} A file:// URI from expo-asset (local files)
allowingReadAccessToURL source.readAccessRoot
source.method, source.body source.body, which makes the request a POST
onFileDownload onDownload, on both platforms: it gets the saved file, not a URL to fetch
sharedCookiesEnabled, pullToRefreshEnabled sharedCookies, pullToRefresh
mediaCapturePermissionGrantType, geolocationEnabled, allowsProtectedMedia onPermissionRequest
clearCache(true), clearHistory, clearFormData, requestFocus call('webView.clearCache', [true]) and so on, on Android; on iOS, call on the data store
nativeConfig A native hook
containerStyle A View around the WebView

Props that became extensions

These props are functions of @react-native-minimal-webview/extensions, which has the setup. Pass each one in the extensions prop. A callback gets the event itself, without react-native-webview's nativeEvent around it:

react-native-webview Here
basicAuthCredential basicAuthCredential
incognito incognito
menuItems, suppressMenuItems, onCustomMenuSelection menuItems
onScroll onScroll
style={{ backgroundColor: 'transparent' }} transparentBackground
hideKeyboardAccessoryView hideKeyboardAccessoryView
keyboardDisplayRequiresUserAction keyboardDisplayRequiresUserAction
refreshControlLightMode refreshControlLightMode
removeIosKeyboardObserver removeIosKeyboardObserver
nestedScrollEnabled nestedScrollEnabled
androidLayerType androidLayerType
Android downloads, downloadingMessage downloadManager
onLoadSubResourceError onLoadSubResourceError, which reports network errors, not the SSL errors react-native-webview's reports
JS dialogs (no prop) dialogs

Settings with another name

react-native-webview ios android
scrollEnabled scrollView.scrollEnabled
showsVerticalScrollIndicator scrollView.<the same name> webView.verticalScrollBarEnabled
showsHorizontalScrollIndicator scrollView.<the same name> webView.horizontalScrollBarEnabled
javaScriptEnabled webpagePreferences.allowsContentJavaScript settings.<the same name>
applicationNameForUserAgent configuration.<the same name> settings.userAgentString (how)
mediaPlaybackRequiresUserAction configuration.mediaTypesRequiringUserActionForPlayback settings.mediaPlaybackRequiresUserGesture
contentMode webpagePreferences.preferredContentMode
decelerationRate scrollView.<the same name>
cacheEnabled: false configuration.websiteDataStore: 'nonPersistent' settings.cacheMode: AndroidConstants.WebSettings.LOAD_NO_CACHE
automaticallyAdjustContentInsets scrollView.contentInsetAdjustmentBehavior
thirdPartyCookiesEnabled webView.acceptThirdPartyCookies
scalesPageToFit settings.useWideViewPort and settings.loadWithOverviewMode
setBuiltInZoomControls settings.builtInZoomControls
setDisplayZoomControls settings.displayZoomControls
forceDarkOn settings.algorithmicDarkeningAllowed; below targetSdk 33 forceDark
saveFormDataDisabled settings.saveFormData: false, a no-op since API 26
webviewDebuggingEnabled webView.inspectable AndroidWebView.setWebContentsDebuggingEnabled(), app-wide
allowFileAccessFromFileURLs preferences.<the same name> settings.<the same name>
allowUniversalAccessFromFileURLs configuration.<the same name> settings.<the same name>

A value keeps its form unless its key takes a constant:

  • mediaPlaybackRequiresUserAction={false} is IOSConstants.AudiovisualMediaTypes.none, and true is all.
  • contentMode is an IOSConstants.ContentMode.
  • decelerationRate is a number: 0.998 for 'normal', 0.99 for 'fast'.

Props with no counterpart

react-native-webview Why
autoManageStatusBarEnabled iOS shows WebKit's own fullscreen
useSharedProcessPool WKProcessPool has had no effect since iOS 15
enableApplePay Apple Pay works with injected scripts since iOS 16
lackPermissionToDownloadMessage onDownload saves into the app's cache, and downloadManager into Downloads: neither needs a permission

Props that keep their name

onNavigationStateChange keeps its name, but fires on every state change, progress and title included. onLoadStart and onLoadEnd keep theirs too, and get the NavigationState instead of a native event. userAgent is the same prop.

Migration recipes

Where a table above says "below", the recipe is here.

onShouldStartLoadWithRequest

Navigation rules replace the callback, and the first rule that matches decides.

import { WebView } from 'react-native-minimal-webview';

// Stands in for what your onShouldStartLoadWithRequest callback decided
const isTrusted = (url: string) => url.startsWith('https://example.com/');

export function Browser() {
  return (
    <WebView
      source={{ uri: 'https://example.com' }}
      navigationRules={[
        { host: ['example.com'], action: 'allow' },
        { scheme: ['http', 'https'], mainFrame: false, action: 'allow' }, // iframes
        { mainFrame: true, action: 'ask' }, // the rest: onNavigationRequest answers
      ]}
      onNavigationRequest={({ url }) => (isTrusted(url) ? 'allow' : 'block')}
      style={{ flex: 1 }}
    />
  );
}

Your rules replace the defaults, defaultNavigationRules: spread it after yours to keep them. A navigation no rule matches is blocked, where react-native-webview opened a URL outside originWhitelist externally.

A late onNavigationRequest answer blocks the navigation, where react-native-webview's Android let it through.

The request has mainFrame in place of isTopFrame, and userInitiated in place of navigationType: 'click'. It has no mainDocumentURL. A new window (onOpenWindow) is a request with newWindow: true.

react-native-webview's iOS also asks about the source load, reloads, back/forward and form POSTs. The rules skip them (navigationRules).

injectJavaScript

evaluate takes an expression, not statements, and resolves with its value.

Wrap the statements you passed injectJavaScript in a function you call, without the trailing true;, as in the scripts example.

postMessage and onMessage

The bridge replaces both, with calls that return promises, and events, in both directions.

Pages that use window.ReactNativeWebView.postMessage and message events keep working with reactNativeWebViewMessages in injectedScripts, so the app can move first and the pages later. The bridge event rnw carries the messages both ways:

import { useEffect, useMemo } from 'react';
import { WebView, createBridge, reactNativeWebViewMessages } from 'react-native-minimal-webview';

type Messages = { reactNative: {}; page: {}; events: { rnw: string } };

export function Shop({ token }: { token: string }) {
  const bridge = useMemo(
    () => createBridge<Messages>({ allowedOrigins: ['https://example.com'] }),
    []
  );

  useEffect(
    () =>
      // onMessage: the page called window.ReactNativeWebView.postMessage(data)
      bridge.on('rnw', (data) => {
        const message = JSON.parse(data) as { type: string };
        // postMessage: the page gets a message event whose data is this string
        if (message.type === 'getToken')
          bridge.emit('rnw', JSON.stringify({ type: 'token', token }));
      }),
    [bridge, token]
  );

  return (
    <WebView
      source={{ uri: 'https://example.com' }}
      bridge={bridge}
      injectedScripts={[reactNativeWebViewMessages]}
      style={{ flex: 1 }}
    />
  );
}

The listener's second argument, { origin } (BridgeSender), takes the place of nativeEvent.url for checking which page sent a message. It is an origin, without the path.

Scroll position

An injected script can report the main frame's scroll position over the bridge, at most once per animation frame. For the offsets during a bounce or a pinch too, use the onScroll extension.

import type { InjectedScript } from 'react-native-minimal-webview';

export const scrollScript: InjectedScript = {
  code: `{ // a block: an origins ['*'] script shares the page's global scope
  let queued = false;
  addEventListener('scroll', () => {
    if (queued) return;
    queued = true;
    requestAnimationFrame(() => { queued = false; window.nativeBridge?.emit('scroll', { x: scrollX, y: scrollY }); });
  }, { passive: true });
}`,
  origins: ['*'], // nativeBridge exists only on the bridge's allowedOrigins
};

Pass it in injectedScripts and listen with bridge.on('scroll', …), as in the bridge example.