Chrome通知最小可运行Demo与扩展版

Vibe Coding 使用 AI 回答

代码问题:

帮我实现一个chrome通知demo

代码解决方案:

下面给出一个最小可运行的 Chrome 通知(Notification)Demo,包含:

  1. 一个极简的 HTML 页面
  2. 一段 JS 代码,负责:
    • 检查并申请通知权限
    • 点击按钮后弹出一条系统级通知
  3. 一个 manifest.json(如果你打算做成扩展)
  4. 运行方式说明(普通网页 vs 扩展)

————————————————— 一、普通网页版(直接双击打开即可测试)

文件:index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Chrome Notification Demo</title>
</head>
<body>
  <h2>Chrome Notification Demo</h2>
  <button id="notifyBtn">显示通知</button>

  <script>
    // 1. 检查/申请权限
    async function ensurePermission() {
      if (!('Notification' in window)) {
        alert('当前浏览器不支持 Notification');
        return false;
      }
      let permission = Notification.permission;
      if (permission === 'granted') return true;
      if (permission === 'denied') {
        alert('用户已拒绝通知权限,请在浏览器设置中手动开启');
        return false;
      }
      // 申请
      permission = await Notification.requestPermission();
      return permission === 'granted';
    }

    // 2. 发送通知
    async function showNotification() {
      const ok = await ensurePermission();
      if (!ok) return;

      const notif = new Notification('Hello!', {
        body: '这是一条来自网页的 Chrome 通知',
        icon: 'https://cdn.jsdelivr.net/gh/devicons/devicon/icons/chrome/chrome-original.svg',
        tag: 'demo',          // 相同 tag 的通知会被合并
        requireInteraction: false
      });

      notif.onclick = () => {
        window.focus();       // 点击后把页面切到前台
        notif.close();
      };
    }

    document.getElementById('notifyBtn').addEventListener('click', showNotification);
  </script>
</body>
</html>

运行方式

  1. 把上面内容保存为 index.html
  2. 用 Chrome 打开 index.html
  3. 首次点击按钮时会弹出权限询问,选择“允许”
  4. 再次点击即可看到系统通知

————————————————— 二、Chrome 扩展版(可选)

如果你想把它做成扩展,需要额外两个文件:

  1. manifest.json(放在根目录)
{
  "manifest_version": 3,
  "name": "Notification Demo",
  "description": "A minimal Chrome extension to show notifications",
  "version": "1.0",
  "action": {
    "default_popup": "index.html"
  },
  "permissions": ["notifications"]
}
  1. 把刚才的 index.html 也放在同一目录,无需改动。

加载扩展

  1. 打开 chrome://extensions
  2. 右上角打开“开发者模式”
  3. 点击“加载已解压的扩展程序”,选择包含 manifest.json 的文件夹
  4. 点击扩展图标,在弹出的 popup 里点“显示通知”即可

————————————————— 三、常见坑

• HTTPS 要求:
普通网页必须在 HTTPS 或 localhost 下才能申请通知权限;本地双击 file:/// 打开时,Chrome 会静默拒绝。
解决:用 VS Code 的 Live Server、Python http.server 或 Nginx 起一个本地 http(s) 服务。

• 扩展 vs 网页:
扩展不需要 HTTPS,但必须把 "notifications" 权限写进 manifest。

• macOS 额外设置:
如果系统级通知被关闭,Chrome 的通知也不会弹。检查系统偏好设置 → 通知 → Google Chrome。

————————————————— 至此,一个最小可运行的 Chrome 通知 Demo 就完成了。