-
-
Save Pokom/8c3aa7c1c444d62cf519ccb2f5940ac2 to your computer and use it in GitHub Desktop.
Puppeteer: monitor status of internet connectivity using headless Chrome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author ebidel@ (Eric Bidelman) | |
* License Apache-2.0 | |
*/ | |
// Uses puppeteer and the browser's online/offline events to monitor connection status. | |
const util = require('util'); | |
const dns = require('dns'); | |
const puppeteer = require('puppeteer'); | |
async function isConnected() { | |
try { | |
const lookupService = util.promisify(dns.lookupService); | |
const result = await lookupService('8.8.8.8', 53); | |
return true; | |
} catch (err) { | |
return false; | |
} | |
} | |
puppeteer.launch().then(async browser => { | |
const page = await browser.newPage(); | |
page.on('online', () => console.info('Online!')); | |
page.on('offline', () => console.info('Offline!')); | |
// Adds window.connectionChange in page. | |
await page.exposeFunction('connectionChange', async online => { | |
// Since online/offline events aren't 100% reliable, do an | |
// actual dns lookup to verify connectivity. | |
const isReallyConnected = await isConnected(); | |
page.emit(isReallyConnected ? 'online' : 'offline'); | |
}); | |
// Monitor browser online/offline events in the page. | |
await page.evaluateOnNewDocument(() => { | |
window.addEventListener('online', e => window.connectionChange(navigator.onLine)); | |
window.addEventListener('offline', e => window.connectionChange(navigator.onLine)); | |
}); | |
// Kick off a navigation so evaluateOnNewDocument runs. | |
await page.goto('data:text/html,hi'); | |
// ... do other stuff ... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While slightly overkill, I love the idea of using this as a startup script for a PI image to join and leave a cluster. Thanks!