Open Mobile App via App Scheme

Hi everyone,

I’m trying to open a mobile app from my web page using the code below. My goal is to achieve the following:

  • If the app is installed, it should open the app directly.
  • If the app is not installed, it should redirect to the app store for installation.

However, I’m facing an issue: when the app is opened and I return to the web page, the timeout still triggers and redirects to the app store.

Is there a way to clear the timeout if the app link is successfully opened? Alternatively, is it possible to detect if the browser failed to open the link so we can handle the redirection to the app store manually, without relying on a timeout?

Any help or guidance would be greatly appreciated. Thank you!
code:

const handleButtonClick = () => {
    const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);

    try {
      console.log(navigator.userAgent);

      window.location.href = isIOS ? iosAppUrl : androidAppUrl;

      const fallbackLink = isIOS
        ? 'https://apps.apple.com' // App Store link for iOS
        : 'https://play.google.com/store/apps/'; // Play Store link for Android

      setTimeout(() => {
        window.location.href = fallbackLink;
      }, 2000);
    } catch (error) {
      console.log('🚀 ~ handleButtonClick ~ error:', error);
    }
  };