帮我实现一个chrome通知demo
下面给出一个最小可运行的 Chrome 通知(Notification)Demo,包含:
————————————————— 一、普通网页版(直接双击打开即可测试)
文件: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>
运行方式
index.htmlindex.html————————————————— 二、Chrome 扩展版(可选)
如果你想把它做成扩展,需要额外两个文件:
{
"manifest_version": 3,
"name": "Notification Demo",
"description": "A minimal Chrome extension to show notifications",
"version": "1.0",
"action": {
"default_popup": "index.html"
},
"permissions": ["notifications"]
}
index.html 也放在同一目录,无需改动。加载扩展
chrome://extensionsmanifest.json 的文件夹————————————————— 三、常见坑
• 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 就完成了。