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

2

6

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?

Shenitashenk answered 1/10, 2021 at 17:46 Comment(1)
Does this answer your question? Expo listen for browser dismissThreewheeler
B
1

Solved this using AppState:

https://reactnative.dev/docs/appstate

if (appState === "active") { // do things after closing the browser }
Brahmana answered 28/10, 2022 at 16:30 Comment(0)
P
0

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

Plenteous answered 14/10, 2021 at 21:44 Comment(1)
I did try something similar with useFocusEffect, however not with the useIsFocused hook. I'll give an another try.Shenitashenk

© 2022 - 2024 — McMap. All rights reserved.