如何在Puppeteer中监听目标站点推送的通知消息
Puppeteer 监听页面通知实现方法
你可以通过监听Puppeteer Page对象的notification事件实现站点通知捕获,具体实现如下:
完整可运行代码
let puppeteer = require('puppeteer') async function run(params) { let brz = await puppeteer.launch({ headless: false }) let context = brz.defaultBrowserContext() // 先配置权限再打开页面,避免页面加载后权限未生效 await context.overridePermissions("https://web.telegram.org/z/", ["geolocation", "notifications"]) let page = await brz.newPage() // 注册通知监听事件,在页面加载前注册避免漏收通知 page.on('notification', notification => { // 打印通知核心内容 console.log('收到新通知:') console.log('通知标题:', notification.title()) console.log('通知内容:', notification.body()) console.log('通知来源URL:', notification.url()) // 可选:关闭通知 // notification.close() }) await page.goto('https://web.telegram.org/z/') } run()
注意要点
- 权限配置要在页面加载前完成,你原代码中
page.goto没有加await且放在权限配置前,会导致页面加载完成后权限才生效,可能触发站点的权限校验失败 notification事件返回的实例支持获取通知的图标、时间戳、点击事件等,你可以根据需求自行扩展对应处理逻辑- 如果需要模拟点击通知的操作,可以调用
notification.click()方法触发站点绑定的通知点击回调
内容的提问来源于stack exchange,提问作者Adhil Muhanmed k
相关产品推荐
相关产品推荐

