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

Chrome扩展如何实现一次仅显示一条通知?

解决Chrome扩展通知重复创建的问题

你的问题核心在于每次调用alert()都会生成全新的UUID作为通知ID,导致Chrome判定为新通知,从而重复显示。以下是两种实用的解决思路:

方案一:固定通知ID(最简单高效)

既然你的通知是用于提示过期标签页,不需要同时显示多个同类型通知,直接用固定ID替代随机UUID即可。Chrome会自动处理重复ID的情况:如果该ID的通知已存在,会更新通知内容而非创建新通知;如果已被用户关闭,则生成新通知。

修改后的alert()函数:

async function alert() {
  console.log("Alert getting created");
  var result = await getExpiredIndices();
  var numberOfExpiredTabs = result.expiredTabArray.length;

  // 用固定ID替代随机UUID
  var id = "expired-tabs-notification";
  var msg = `Ta daa! Your tab(s) are ready.`;
  
  chrome.notifications.create(
    id,
    {
      type: "basic",
      iconUrl: "assets/icons/pondr_128.png",
      title: "Pondr",
      message: msg,
      priority: 2,
      requireInteraction: true,
      buttons: [
        { title: "Open" },
        { title: "Later" },
      ],
    }
  );
}

方案二:主动检查已有通知

如果需要更精细的控制(比如判断通知是否处于活跃状态),可以用chrome.notifications.getAll()获取当前所有活跃通知,确认目标通知不存在后再创建:

async function alert() {
  console.log("Alert getting created");
  var result = await getExpiredIndices();
  var numberOfExpiredTabs = result.expiredTabArray.length;

  const targetNotifId = "expired-tabs-notification";
  // 获取所有活跃通知
  const notifications = await chrome.notifications.getAll();
  
  // 目标通知已存在则直接返回
  if (notifications[targetNotifId]) {
    console.log("通知已存在,无需重复创建");
    return;
  }

  var msg = `Ta daa! Your tab(s) are ready.`;
  chrome.notifications.create(
    targetNotifId,
    {
      type: "basic",
      iconUrl: "assets/icons/pondr_128.png",
      title: "Pondr",
      message: msg,
      priority: 2,
      requireInteraction: true,
      buttons: [
        { title: "Open" },
        { title: "Later" },
      ],
    }
  );
}

额外优化:点击按钮后关闭通知

在按钮点击回调中,建议调用chrome.notifications.clear()关闭当前通知,避免通知一直停留在通知中心:

chrome.notifications.onButtonClicked.addListener(async function (notifId, btnIdx) {
  // 先关闭当前通知
  await chrome.notifications.clear(notifId);

  var result1 = await getExpiredIndices();
  var result2 = await getAllTabsArray();
  var expiredTabArray = result1.expiredTabArray;
  var allTabsArray = result2.allTabsArray;

  if (btnIdx === 0) {
    console.log("hit yes");
    console.log("Before popping allTabsArray: ", allTabsArray);
    console.log("Before popping expiredTabsArray: ", expiredTabArray);
    openTabsNow(expiredTabArray, allTabsArray);
  } else if (btnIdx === 1) {
    console.log("hit later");
    console.log("Before popping allTabsArray: ", allTabsArray);
    console.log("Before popping expiredTabsArray: ", expiredTabArray);
    openTabsLater(expiredTabArray, allTabsArray);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:01:15