如何以编程方式读取Chromium接收的网页推送通知?
拦截处理Chromium网页推送通知实现方案
方案一:Puppeteer实现(推荐)
该方案可以精准控制通知的拦截、内容提取、自定义处理逻辑,适配单站点/全站点场景。
实现代码示例
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false, // 无头模式可填 'new' args: ['--enable-notifications'] }); // 给所有新打开的页面绑定通知监听 browser.on('targetcreated', async (target) => { if (target.type() === 'page') { const page = await target.page(); // 授予当前页面通知权限 await page.setPermission({ origin: page.url() }, 'notifications', 'granted'); // 监听通知事件 page.on('notification', async (notification) => { // 提取通知核心字段 const notifyInfo = { title: notification.title(), body: notification.body(), icon: notification.icon(), timestamp: notification.timestamp() }; console.log('拦截到推送通知:', notifyInfo); // 自定义处理逻辑:例如关闭通知不弹出、写入日志、触发业务回调等 // await notification.close(); }); } }); const page = await browser.newPage(); await page.goto('目标站点地址'); })();
方案二:Ubuntu/Debian系统层面Bash实现
适合不需要精细化控制、希望全局生效的场景,分为全局禁用和监听拦截两种模式。
模式1:全局禁用Chromium所有通知
通过修改Chromium系统策略实现,永久生效:
# 创建策略目录(不存在则新建) sudo mkdir -p /etc/opt/chromium/policies/managed # 写入禁用通知策略 sudo bash -c 'cat > /etc/opt/chromium/policies/managed/notifications_policy.json << EOF { "DefaultNotificationsSetting": 2 } EOF'
DefaultNotificationsSetting取值说明:1为全局允许通知,2为全局禁止通知,修改后重启Chromium即可生效
模式2:监听拦截并处理通知
Linux桌面环境下Chromium的通知默认通过DBus总线发送,可通过监听DBus事件实现拦截处理:
- 先安装依赖工具:
sudo apt update && sudo apt install -y dbus-x11
- 拦截处理脚本示例:
#!/bin/bash # 监听DBus通知总线,过滤Chromium发出的通知 dbus-monitor "interface='org.freedesktop.Notifications',member='Notify'" | while read -r line; do if echo "$line" | grep -qi "chromium"; then echo "拦截到Chromium推送通知: $line" # 自定义处理逻辑:例如提取内容写入日志、调用接口转发、关闭通知不弹出等 fi done
内容的提问来源于stack exchange,提问作者stkvtflw
相关产品推荐
相关产品推荐

