Skip to content

Instantly share code, notes, and snippets.

@montasim
Created June 26, 2024 06:53
Show Gist options
  • Save montasim/e1fe31efe1788c01135aad396d3e4d95 to your computer and use it in GitHub Desktop.
Save montasim/e1fe31efe1788c01135aad396d3e4d95 to your computer and use it in GitHub Desktop.
This script automatically refreshes a given webpage at specified intervals using Puppeteer. It is designed to monitor changes on a webpage over time. This version includes better error handling and resource management to ensure the script runs efficiently.
/**
* @file This script automatically refreshes a given webpage at specified intervals using Puppeteer.
* It is designed to monitor changes on a webpage over time. This version includes better error handling
* and resource management to ensure the script runs efficiently.
*/
const puppeteer = require('puppeteer');
let browser;
const refreshUrl = 'https://profile-counter.glitch.me/montasim/count.svg';
/**
* Initializes Puppeteer browser if not already initialized.
*/
const initBrowser = async () => {
if (!browser) {
browser = await puppeteer.launch();
}
};
/**
* Automatically refreshes the specified URL at the given interval. This function uses `setTimeout`
* instead of `setInterval` to avoid overlaps of refresh cycles.
*
* @param {string} url - The URL of the page to refresh.
* @param {number} interval - The interval in milliseconds at which the page should be refreshed.
*/
const autoRefresh = async (url, interval) => {
await initBrowser();
const page = await browser.newPage();
const refreshPage = async () => {
try {
await page.goto(url);
console.log('Page refreshed');
setTimeout(refreshPage, interval); // Schedule the next refresh
} catch (error) {
console.error('Failed to refresh page:', error);
await page.close();
}
};
refreshPage();
};
// Example usage: Refresh a URL every 5 seconds.
autoRefresh(refreshUrl, 5000);
/**
* Gracefully close the browser when the process exits.
*/
process.on('exit', () => {
if (browser) {
console.log('Closing browser');
browser.close();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment