Skip to content

Instantly share code, notes, and snippets.

@diachedelic
Last active June 25, 2024 18:17
Show Gist options
  • Save diachedelic/0d60233dab3dcae3215da8a4dfdcd434 to your computer and use it in GitHub Desktop.
Save diachedelic/0d60233dab3dcae3215da8a4dfdcd434 to your computer and use it in GitHub Desktop.
Deep link to a native app from a browser, with a fallback
@cody-dashka
Copy link

cody-dashka commented Oct 27, 2023

try this.

function openDeepLink(url: string, options?: Partial<{ onOpen?: () => void; onFail?: () => void; waitTime?: number }>) {
  let timeout: NodeJS.Timeout;
  let interval: NodeJS.Timer;
  let visible: DocumentVisibilityState = 'visible';

   const handleOpen = () => {
      window.removeEventListener('visibilitychange', () => true);
      options?.onOpen?.();
  };
  const handleResponse = () => {
    if (visible === 'visible') return options?.onFail?.();
    clearInterval(interval);
    handleOpen();
  };

  try {
    window.addEventListener('visibilitychange', (e) => (visible = (e.target as Document)?.visibilityState));
    timeout = setTimeout(handleResponse, options?.waitTime || 5000);

    interval = setInterval(() => {
      if (visible === 'hidden') {
        clearTimeout(timeout);
        handleResponse();
      }
    }, options?.waitTime || 5000);

    window.location.href = url;
  } catch (error) {
    options?.onFail?.();
  }
}

openDeepLink("fb://profile/100004452732850", {onOpen: console.log, onFail: console.error});

@MTPGI
Copy link

MTPGI commented Mar 25, 2024

Tested on last version of Firefox 124, Android 13. Not working because even if a dialog appears to redirect to the app, the pages doesn't loose focus.

@diachedelic
Copy link
Author

Can it be fixed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment