react-native-inappbrowser-reborn

repository·develop·Indexed 23 days ago

https://github.com/proyecto26/react-native-inappbrowser

A React Native library providing access to system web browsers using Chrome Custom Tabs on Android and SafariServices/AuthenticationServices on iOS. It supports standard web view opening via open(), specialized authentication flows via openAuth() for OAuth and deep linking, and Android-specific performance optimizations like browser warmup and pre-rendering URLs.

Tokens
3.3K
Snippets
7
Records
17
Agent score
31%

What's inside react-native-inappbrowser-reborn

  1. Implement Authentication Flow with Deep Linking

    develop

    To redirect users back to your app from a web browser during an OAuth flow, you must configure deep linking.

    1. Configure Native Platforms

    Android (AndroidManifest.xml): Add an <intent-filter> to your activity with your custom scheme and host.

    <activity
      ...
      android:launchMode="singleTask">
      <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="my-scheme" android:host="my-host" android:pathPrefix="" />
      </intent-filter>
    </activity>

    iOS (Info.plist): Add your scheme to CFBundleURLTypes.

    <key>CFBundleURLTypes</key>
    <array>
      <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLName</key>
        <string>my-scheme</string>
        <key>CFBundleURLSchemes</key>
        <array>
          <string>my-scheme</string>
        </array>
      </dict>
    </array>

    2. Use openAuth in JavaScript

    When initiating login, use InAppBrowser.openAuth. The redirectUrl parameter should match the deep link scheme you configured.

    const deepLink = getDeepLink('callback')
    const url = `https://my-auth-login-page.com?redirect_uri=${deepLink}`
    
    try {
      if (await InAppBrowser.isAvailable()) {
        const response = await InAppBrowser.openAuth(url, deepLink, {
          ephemeralWebSession: false,
          showTitle: false,
          enableUrlBarHiding: true,
          enableDefaultShare: false
        })
        
        if (response.type === 'success' && response.url) {
          // Handle the successful redirect URL
          Linking.openURL(response.url)
        }
      } else {
        Linking.openURL(url)
      }
    } catch (error) {
      Linking.openURL(url)
    }
  2. Manage StatusBar style when opening the browser

    develop

    The StatusBar will maintain its last state when the browser is opened. To ensure the status bar style is restored correctly after the browser is dismissed, use StatusBar.pushStackEntry and popStackEntry (for React Native 0.59+).

    async openInBrowser(url) {
      try {
        const oldStyle = StatusBar.pushStackEntry({ barStyle: 'dark-content', animated: false });
        await InAppBrowser.open(url)
        StatusBar.popStackEntry(oldStyle);
      } catch (error) {
        Alert.alert(error.message)
      }
    }
  3. Optimize Android Browser Performance

    develop

    To improve launch speed on Android, you can warm up the in-app browser client.

    1. Initialize the service in MainActivity.java: Add RNInAppBrowserModule.onStart(this) to your onStart method.

    2. Pre-render likely URLs: Use InAppBrowser.mayLaunchUrl to tell the browser which URLs the user is likely to visit. This should be called inside a useEffect (or similar lifecycle method) and not on every render.

    useEffect(() => {
      InAppBrowser.mayLaunchUrl("Url user has high chance to open", ["Other urls that user might open ordered by priority"]);
    }, []);
    import com.proyecto26.inappbrowser.RNInAppBrowserModule;
    
    public class MainActivity extends ReactActivity {
    
      @Override
      protected void onStart() {
        super.onStart();
        RNInAppBrowserModule.onStart(this);
      }
    
    }
  4. Configure manual installation for Android

    develop

    For manual Android installation, follow these steps:

    1. MainApplication.java: Import com.proyecto26.inappbrowser.RNInAppBrowserPackage and add new RNInAppBrowserPackage() to the getPackages() method.
    2. settings.gradle: Append the following:
      include ':react-native-inappbrowser-reborn'
      project(':react-native-inappbrowser-reborn').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-inappbrowser-reborn/android')
    3. app/build.gradle: Add implementation project(':react-native-inappbrowser-reborn') to the dependencies block.
    4. ProGuard (Optional): To prevent code stripping, add these rules to proguard-rules.pro:
      -keepattributes *Annotation*
      -keepclassmembers class ** { @org.greenrobot.eventbus.Subscribe <methods>; }
      -keep enum org.greenrobot.eventbus.ThreadMode { *; }
    include ':react-native-inappbrowser-reborn'
    project(':react-native-inappbrowser-reborn').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-inappbrowser-reborn/android')
  5. Configure manual installation for iOS (Xcode/Podfile)

    develop

    If autolinking is not used, you can install manually via Xcode or Podfile.

    Using Podfile (Recommended):

    1. Add pod 'RNInAppBrowser', :path => '../node_modules/react-native-inappbrowser-reborn' to your ios/Podfile.
    2. Run pod install.

    Using Xcode:

    1. In Xcode, right-click LibrariesAdd Files to [your project's name].
    2. Add RNInAppBrowser.xcodeproj from node_modules/react-native-inappbrowser-reborn.
    3. Select your project in Xcode, go to Build PhasesLink Binary With Libraries, and add libRNInAppBrowser.a.
  6. Configure automatic installation for React Native >= 0.60

    develop

    For React Native versions 0.60 and above, autolinking is supported. You only need to perform platform-specific steps:

    iOS: Run pod install in your ios directory.

    Android: Depending on whether you use Android Support libraries or AndroidX, you must configure your android/build.gradle file.

    $ cd ios && pod install && cd ..
  7. Configure Android build.gradle for Android Support libraries

    develop

    If your project uses Android Support libraries, ensure your android/build.gradle contains the following configuration:

    buildscript {
      ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        // Only using Android Support libraries
        supportLibVersion = "28.0.0"
      }
    }
  8. Configure Android build.gradle for AndroidX

    develop

    If your project uses AndroidX, modify your android/build.gradle to remove supportLibVersion and specify AndroidX library versions:

    buildscript {
      ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
        ndkVersion = "21.4.7075529"
        // Remove 'supportLibVersion' property and put specific versions for AndroidX libraries
        androidXAnnotation = "1.2.0"
        androidXBrowser = "1.3.0"
        // Put here other AndroidX dependencies
      }
    }
  9. InAppBrowser API Methods

    develop

    The InAppBrowser module provides several methods for managing web browser sessions.

    • open(url, options): Opens a URL using SFSafariViewController on iOS (in a modal) or Chrome Custom Tabs on Android. Note that on iOS, the modal Safari does not share cookies with the system Safari.
    • close(): Dismisses the currently presented web browser.
    • openAuth(url, redirectUrl, options): Opens a URL specifically for authentication using SFAuthenticationSession/ASWebAuthenticationSession on iOS and Chrome Custom Tabs on Android. On iOS, users are prompted to allow the app to authenticate via the provided URL (ideal for OAuth flows with deep linking).
    • closeAuth(): Dismisses the current authentication session.
    • isAvailable(): Returns a boolean indicating if the device supports this plugin.
    • onStart(): (Android Only) Initializes a bound background service to allow the app to communicate with the browser. This is used to warm up the browser or indicate future navigation.
    • warmup(): (Android Only) Warms up the browser process to make navigation faster.
    • mayLaunchUrl(primaryUrl, [secondaryUrls]): (Android Only) Notifies the browser of likely future navigations. The first URL is the highest priority. Subsequent URLs are treated with decreasing priority.
  10. Configure Android InAppBrowser Options

    develop

    When calling open or openAuth on Android, you can pass the following properties in the options object:

    • showTitle (Boolean): Whether to show the title in the custom tab.
    • toolbarColor (String): Color of the toolbar.
    • secondaryToolbarColor (String): Color of the secondary toolbar.
    • navigationBarColor (String): Color of the navigation bar.
    • navigationBarDividerColor (String): Color of the navigation bar divider.
    • enableUrlBarHiding (Boolean): Enables the URL bar to hide as the user scrolls down.
    • enableDefaultShare (Boolean): Adds a default share item to the menu.
    • animations (Object): Sets start and exit animations. Keys: startEnter, startExit, endEnter, endExit. Values should be resource identifiers (e.g., package:anim/name or just the resource name).
    • headers (Object): Key/value pairs sent in the HTTP request headers. Example: { 'Authorization': 'Bearer ...' }.
    • forceCloseOnRedirection (Boolean): Opens Custom Tab in a new task to avoid redirection issues back to the app scheme.
    • hasBackButton (Boolean): Uses a back arrow instead of the default X icon to close the tab.
    • browserPackage (String): Package name of the browser to use for Custom Tabs.
    • showInRecents (Boolean): Whether the browsed website appears as a separate entry in Android recents/multitasking.
    • includeReferrer (Boolean): Whether to include your package name as a referrer.
  11. Configure iOS InAppBrowser Options

    develop

    When calling open or openAuth on iOS, you can pass the following properties in the options object:

    • dismissButtonStyle (String): Style of the dismiss button. Options: done, close, cancel.
    • preferredBarTintColor (String): Background color of the navigation bar and toolbar. Example: #FFFFFF.
    • preferredControlTintColor (String): Color of control buttons on the navigation bar and toolbar. Example: #808080.
    • readerMode (Boolean): Whether to enter Safari Reader mode if available.
    • animated (Boolean): Whether to animate the presentation.
    • modalPresentationStyle (String): Presentation style for view controllers. Options: automatic, none, fullScreen, pageSheet, formSheet, currentContext, custom, overFullScreen, overCurrentContext, popover.
    • modalTransitionStyle (String): Transition style. Options: coverVertical, flipHorizontal, crossDissolve, partialCurl.
    • modalEnabled (Boolean): Whether to present SafariViewController modally or as a push.
    • enableBarCollapsing (Boolean): Whether the browser's toolbars collapse.
    • ephemeralWebSession (Boolean): Prevents re-use of cookies from previous sessions (use with openAuth).
    • formSheetPreferredContentSize (Object): Custom size for iPad formSheet modals. Example: {width: 400, height: 500}.