Skip to content

Instantly share code, notes, and snippets.

@iMrDJAi
Created June 21, 2024 22:58
Show Gist options
  • Save iMrDJAi/0ba5a58aba5c209d691a9d1508602d2e to your computer and use it in GitHub Desktop.
Save iMrDJAi/0ba5a58aba5c209d691a9d1508602d2e to your computer and use it in GitHub Desktop.
Monitor browser notifications using puppeteer.
import puppeteer from 'puppeteer-core'
main()
async function main() {
let page, browser
try {
browser = await connectBrowser()
page = await browser.newPage()
await page.goto('https://x.com/settings/push_notifications', {
waitUntil: "networkidle2"
})
await new Promise(res => setTimeout(res, 5000))
let len = 0
await (async function interval() {
const notifications = await page.evaluate(() => (
navigator.serviceWorker.ready.then(registration => (
registration.getNotifications().then(notifications => {
return notifications.map(n => ({
badge: n.badge,
body: n.body,
data: n.data,
dir: n.dir,
icon: n.icon,
image: n.image,
lang: n.lang,
renotify: n.renotify,
requireInteraction: n.requireInteraction,
silent: n.silent,
tag: n.tag,
timestamp: n.timestamp,
title: n.title
}))
})
))
))
console.log(notifications.length + ' Notifications')
if (len !== notifications.length) {
console.log(notifications[notifications.length - 1])
}
len = notifications.length
await new Promise(res => setTimeout(res, 500))
interval()
})()
} catch(err) {
console.error('ERROR!', err)
} finally {
console.log('STOPING...')
page?.close()
await new Promise(res => setTimeout(res, 200))
browser?.disconnect()
}
}
async function connectBrowser() {
let port = process.env.PORT || 21224
const res = await fetch(`http://localhost:${port}/json/version`)
const data = await res.json()
const browser = await puppeteer.connect({
browserWSEndpoint: data.webSocketDebuggerUrl,
defaultViewport: {
width: 1280,
height: 600
}
})
return browser
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment