Flutter InAppWebView打开whatsapp.com链接出现空白页问题求助
问题根因
- 该问题由
flutter_inappwebview 5.3.2对JS动态触发跳转的默认兼容逻辑缺失导致:WhatsApp站点启用JS时,站内链接多为JS动态生成跳转(非原生<a>标签跳转,部分走window.open、伪协议触发逻辑),默认配置下WebView未捕获到这类跳转的完整地址,才会出现onLoadStart返回空字符串、跳转空白页的情况。 - 禁用JS后站点跳转回落为原生
<a>标签逻辑,直接传initialUrl也是走原生加载逻辑,因此不会触发问题。
修复步骤
1. 基础配置补全
先开启窗口创建支持、允许JS打开窗口,基础配置示例:
InAppWebViewGroupOptions options = InAppWebViewGroupOptions( crossPlatform: InAppWebViewOptions( javaScriptEnabled: true, // 允许JS打开窗口 javaScriptCanOpenWindowsAutomatically: true, supportMultipleWindows: true, // 禁止自动拦截自定义scheme allowUniversalAccessFromFileURLs: true, ), android: AndroidInAppWebViewOptions( useHybridComposition: true, // 开启DOM存储,适配WhatsApp站点缓存逻辑 domStorageEnabled: true, ), ios: IOSInAppWebViewOptions( allowsInlineMediaPlayback: true, ) );
2. 重写shouldOverrideUrlLoading拦截跳转
该回调优先级高于页面加载逻辑,可在跳转前捕获到完整URL,避免空地址加载:
shouldOverrideUrlLoading: (controller, navigationAction) async { var requestUrl = navigationAction.request.url?.toString() ?? ""; // 过滤空地址、伪协议地址 if (requestUrl.isEmpty || requestUrl.startsWith("javascript:") || requestUrl.startsWith("blob:")) { // 若为空白跳转直接终止当前加载 return NavigationActionPolicy.CANCEL; } // 正常地址放行 return NavigationActionPolicy.ALLOW; },
3. 处理onCreateWindow新窗口跳转逻辑
WhatsApp部分链接会触发新窗口打开,不处理该回调会出现空白页:
onCreateWindow: (controller, createWindowAction) async { // 捕获新窗口的跳转地址 String? targetUrl = createWindowAction.request.url?.toString(); if (targetUrl != null && targetUrl.isNotEmpty) { // 直接在当前WebView加载新地址,也可根据业务逻辑新开WebView实例加载 await controller.loadUrl(urlRequest: URLRequest(url: Uri.parse(targetUrl))); } return true; },
按以上配置修改后即可正常捕获WhatsApp站点JS触发的所有跳转,不会再出现空白页问题。
内容的提问来源于stack exchange,提问作者newbiedev
相关产品推荐
相关产品推荐

