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

Cordova项目iOS14 Widget点击条目如何捕获URL跳转对应应用内页面

解决步骤

1. 首先确认Widget侧的URL格式合规

你用到了两种deeplink插件,需要保证Widget传递的URL符合以下任意一种规则:

  • 自定义scheme格式:比如你配置的scheme://article/xxx(对应cordova-plugin-customurlscheme插件的配置)
  • 通用链接格式:比如https://你配置的UL域名/article/xxx(对应cordova-universal-links-plugin的关联域名配置)
    如果URL是未关联的普通http/https链接,系统只会启动应用不会传递到插件层。

2. 适配iOS SceneDelegate回调(核心问题)

iOS14+ Widget触发的应用跳转,默认走SceneDelegate的回调方法,而你用到的两个Cordova插件大多只适配了旧版AppDelegate的回调,导致只启动应用拿不到URL。
在你的iOS项目的SceneDelegate文件中添加以下代码:

Swift版本:

// 处理自定义scheme跳转场景
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    // 把URL通知给cordova-plugin-customurlscheme插件
    NotificationCenter.default.post(name: NSNotification.Name("CDVOpenURLNotification"), object: url)
}

// 处理Universal Link跳转场景
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, 
          let url = userActivity.webpageURL else { return }
    // 把UserActivity通知给cordova-universal-links-plugin插件
    NotificationCenter.default.post(name: NSNotification.Name("CDVLaunchURL"), object: userActivity)
}

Objective-C版本:

// 处理自定义scheme跳转场景
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
    NSURL *url = URLContexts.firstObject.URL;
    if (url) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CDVOpenURLNotification" object:url];
    }
}

// 处理Universal Link跳转场景
- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity {
    if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb] && userActivity.webpageURL) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CDVLaunchURL" object:userActivity];
    }
}

3. 补全冷启动场景的URL捕获

如果用户完全杀掉应用后点击Widget,URL会存在启动参数里,需要在应用初始化完成后主动读取:

document.addEventListener('deviceready', () => {
  // 读取冷启动的自定义scheme URL
  if (window.launchUrl) {
    console.log('冷启动获取的Widget跳转URL:', window.launchUrl)
    main.onOpenApplicationLinks(window.launchUrl)
    delete window.launchUrl
  }
  // 读取冷启动的Universal Link URL
  universalLinks.getLaunchEvent((eventData) => {
    if (eventData) {
      console.log('冷启动获取的Widget跳转URL:', eventData.url)
      main.onOpenApplicationLinks(eventData.url)
    }
  })
}, false)

4. 验证效果

分别测试两种场景:

  • 应用在后台存活时点击Widget,查看window.handleOpenURL或universalLinks.subscribe的回调日志
  • 完全杀掉应用后点击Widget,查看deviceready回调中的日志

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:45:03