You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Android端InAppBrowser setTimeout自动关闭失效问题

Android端InAppBrowser自动关闭失效问题解决方案

问题根源

Android平台上,InAppBrowser.open()返回的Promise仅在用户手动关闭浏览器后才会resolve,导致代码中的await InAppBrowser.open()会阻塞整个openInAppBrowser函数,直到浏览器关闭才继续执行后续逻辑。由于JS是单线程模型,setTimeout的回调会被挂起,必须等阻塞解除(手动关闭浏览器)才会执行。iOS端无此问题,因为InAppBrowser.open()的Promise会立即resolve,不会阻塞主线程。

修复方案

修改openInAppBrowser函数,移除对InAppBrowser.open()的await,让函数立即返回,避免阻塞主线程,确保setTimeout的回调能按时触发。

修改后的完整代码

const onclick = () => {
  openInAppBrowser('https://www.google.com/');
  setTimeout(() => {
    close();
  }, 9000);
};

export const openInAppBrowser = async (url: string) => {
  try {
    if (await InAppBrowser.isAvailable()) {
      const options: InAppBrowserOptions = {
        showTitle: false,
        toolbarColor: 'black',
        secondaryToolbarColor: 'black',
        enableUrlBarHiding: true,
        enableDefaultShare: true,
        forceCloseOnRedirection: false,
        enableBarCollapsing: true
      };

      // 移除await,避免阻塞主线程
      InAppBrowser.open(url, options);
    } else {
      Linking.openURL(url);
    }
  } catch (error) {
    console.log(error);
  }
};

export const close = async (): Promise<void> => {
  try {
    await InAppBrowser.close();
  } catch (error) {
    throw new Error(error as any);
  }
};

额外优化建议

如果需要避免页面加载缓慢导致定时器提前触发的问题,可以监听浏览器加载完成事件,确保页面加载后再启动定时器:

export const openInAppBrowser = async (url: string) => {
  try {
    if (await InAppBrowser.isAvailable()) {
      const options: InAppBrowserOptions = {
        showTitle: false,
        toolbarColor: 'black',
        secondaryToolbarColor: 'black',
        enableUrlBarHiding: true,
        enableDefaultShare: true,
        forceCloseOnRedirection: false,
        enableBarCollapsing: true
      };

      InAppBrowser.open(url, options);
      // 监听页面加载完成事件,再启动定时器
      InAppBrowser.addEventListener('loadstop', () => {
        setTimeout(() => {
          close();
        }, 9000);
      });
    } else {
      Linking.openURL(url);
    }
  } catch (error) {
    console.log(error);
  }
};

内容的提问来源于stack exchange,提问作者Lelouch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:27:42