Created
February 23, 2024 10:32
-
-
Save anushshukla/e5c53e683c8b4c0d59e237d66f6932e8 to your computer and use it in GitHub Desktop.
Simple full page screenshot script
This file contains 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
(async () => { | |
const delay = ms => new Promise(res => setTimeout(res, ms)); | |
// Function to load script dynamically | |
const loadScript = (url) => { | |
return new Promise((resolve, reject) => { | |
const script = document.createElement('script'); | |
script.src = url; | |
script.onload = resolve; | |
script.onerror = reject; | |
document.head.appendChild(script); | |
}); | |
}; | |
try { | |
await loadScript('https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-alpha2/html2canvas.min.js'); | |
const scrollHeight = document.documentElement.scrollHeight; | |
let scrollPosition = 0; | |
while (scrollPosition < scrollHeight) { | |
window.scrollBy(0, window.innerHeight); | |
await delay(200); // Adjust the delay as needed | |
scrollPosition += window.innerHeight; | |
} | |
await delay(1000); // Adjust the delay as needed for content to settle | |
html2canvas(document.body, { | |
scrollX: 0, | |
scrollY: 0, | |
windowWidth: document.documentElement.scrollWidth, | |
windowHeight: document.documentElement.scrollHeight | |
}).then(canvas => { | |
// Convert canvas to data URL | |
const dataURL = canvas.toDataURL('image/png'); | |
// Create a temporary link element | |
const link = document.createElement('a'); | |
link.href = dataURL; | |
link.download = 'screenshot.png'; | |
// Append link to body and click it to trigger download | |
document.body.appendChild(link); | |
link.click(); | |
// Clean up | |
document.body.removeChild(link); | |
}).catch(error => { | |
console.error('Failed to take screenshot:', error); | |
}); | |
} catch (error) { | |
console.error('Failed to load html2canvas:', error); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment