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

安卓版Firefox点击通知打开about:blank的问题及解决咨询

问题描述

在Web Worker中实现了通知点击事件处理逻辑,代码如下:

self.addEventListener('notificationclick', (event) => {
  event.notification.close();

  const link = event.notification.data?.link || self.location.origin

  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for(const client of clientList)
        if(client.url === link && "focus" in client) return client.focus();

      try
      {
        if(clients.openWindow) return clients.openWindow(link);
      }
      catch (error) {
        console.error('catch', err);
      }
    })
  );
});

该逻辑在Ubuntu系统的Firefox、Ubuntu和安卓系统的Chrome中均可正常工作,但在安卓版Firefox中点击通知会打开新标签页显示about:blank。

问题分析与解决办法

核心原因

安卓版Firefox在Service Worker的clients.matchAll和clients.openWindowAPI处理上存在兼容性差异:

  • includeUncontrolled: true参数可能未被正确支持,导致无法匹配到非受控的客户端窗口;
  • clients.openWindow在安卓Firefox中对URL的解析或权限校验更严格,若匹配客户端失败后,URL处理异常会打开about:blank;
  • 代码中错误捕获存在变量名错误(err应为error),可能掩盖真实问题。

修复方案

  • 简化客户端匹配逻辑:先尝试匹配受控客户端,若未找到再尝试包含非受控的,避免兼容性问题;
  • 确保URL有效性:显式验证link是否为合法的绝对URL,避免默认值或传入值不符合安卓Firefox的要求;
  • 修复错误捕获变量:统一错误变量名,便于排查问题;
  • 强化Promise处理:确保waitUntil包裹的Promise链完整,避免因返回值异常导致的行为错误。

修改后的代码示例

self.addEventListener('notificationclick', (event) => {
  event.notification.close();

  // 确保link是合法的绝对URL
  const link = event.notification.data?.link 
    ? new URL(event.notification.data.link, self.location.origin).href 
    : self.location.origin;

  event.waitUntil(
    (async () => {
      // 先尝试匹配受控窗口
      let clientList = await clients.matchAll({ type: 'window' });
      for (const client of clientList) {
        if (client.url.startsWith(link) && 'focus' in client) {
          return client.focus();
        }
      }
      // 再尝试匹配非受控窗口(兼容处理)
      clientList = await clients.matchAll({ type: 'window', includeUncontrolled: true });
      for (const client of clientList) {
        if (client.url.startsWith(link) && 'focus' in client) {
          return client.focus();
        }
      }
      // 打开新窗口
      if (clients.openWindow) {
        try {
          return await clients.openWindow(link);
        } catch (error) {
          console.error('打开窗口失败:', error);
        }
      }
    })()
  );
});

额外说明

  • 使用startsWith替代严格相等的===,避免URL参数或哈希差异导致匹配失败;
  • 用async/await重构代码,提升可读性和Promise链的稳定性;
  • 显式构造URL确保路径合法性,避免相对路径或异常URL导致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:02:43