Expo: How to detect when a WebBrowser instance is closed by the user?

Viewed 735

I have an Expo app that will open some web page with a redirect to expo itself. On that case, this is to perform 3DS callbacks. Here is a very simplified version:

import React, {
  FC, useEffect, useState,
} from 'react';
import * as Linking from 'expo-linking';
import * as WebBrowser from 'expo-web-browser';
import {
  Button,
} from '@private/apps-components';
import {
  ButtonProps,
  View,
} from 'react-native';

export const MyComponent: FC = () => {
  const [loading, setLoading] = useState<boolean>(false);

  const urlEventHandler = async (event): Promise<void> => {
    console.log('url-event', event);
    setLoading(false);
    // Stuff...
  };

  useEffect(() => {
    Linking.addEventListener('url', urlEventHandler);

    return () => Linking.removeEventListener('url', urlEventHandler);
  }, []);

  const handlePress: ButtonProps['onPress'] = () => {
    setLoading(false);
    WebBrowser.openBrowserAsync(aRandomUrlThatWillRedirectToTheApp, {
      showInRecents: true,
    })

  }

  return (
    <View>
      <Button
        title="Test"
        onPress={handlePress}
        loading={loading}
      />
    </View>
  );
};

export default null;

This is working. However, if the customer close the navigator before the web redirect is being processed, the app is stuck on the loading state.

The question is: How to detect if a user has closed the opened WebBrowser?

1 Answers

I haven't actually tested this - could follow up - but you could probably use react-navigation to detect whether the component is in focus or not. IE when you open the web browser, the component is not in focus, but when you close the web browser, the component is back in focus.

For react navigation version 4 you would wrap the component in withNavigationFocus in order to achieve this: https://reactnavigation.org/docs/4.x/function-after-focusing-screen#triggering-an-action-with-the-withnavigationfocus-higher-order-component. For 5, and 5+, you can use the useIsFocused hook: https://reactnavigation.org/docs/5.x/function-after-focusing-screen/#re-rendering-screen-with-the-useisfocused-hook

Related