Skip to content

Instantly share code, notes, and snippets.

@Pokom
Forked from ebidel/monitor_internet_connection.js
Created December 31, 2017 19:41
Show Gist options
  • Save Pokom/8c3aa7c1c444d62cf519ccb2f5940ac2 to your computer and use it in GitHub Desktop.
Save Pokom/8c3aa7c1c444d62cf519ccb2f5940ac2 to your computer and use it in GitHub Desktop.
Puppeteer: monitor status of internet connectivity using headless Chrome
/**
* @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 ...
});
@Pokom
Copy link
Author

Pokom commented Dec 31, 2017

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment