. SPA, document.location.href. MutationObserver. . , ( , ). ( , ). navigator.sendBeacon:
const settings = {
botId: '...',
chatId: '...',
userName: 'Matvey',
pollingInterval: 10000
}
const mutedUrls = [
'https://gmail.com',
'https://www.eduka.lt',
]
const sendMessage = (type, href) => {
if (mutedUrls.find(url => href.startsWith(url))) { return false }
const data = new FormData()
data.append('chat_id', settings.chatId)
data.append('text', `${settings.userName} ${type} ${document.title} ${href}`)
navigator.sendBeacon(
`https://api.telegram.org/bot${settings.botId}/sendMessage`,
data
)
}
let latestHref = null
let timeout = 0
const run = () => {
if (window.location.href !== latestHref) {
latestHref = window.location.href
sendMessage('opened', latestHref)
}
timeout && clearTimeout(timeout)
timeout = setTimeout(run, settings.pollingInterval)
}
window.addEventListener('load', run)
window.addEventListener('unload', () => sendMessage('closed', latestHref))